Search code examples
postgresqlgrafana

Dynamic number of series with one query in Grafana


Is there a way to get multiple series in one query using Postgres connection in Grafana? Let’s say I have 5 attributes associated to my data and I’d like to display 5 series using one query so it’s dynamic.

When one attribute is added or removed, so is done with series.

attribute | bits    | created_at
------------------------------
1         | 44632   | <datetime>
4         | 124854  | <datetime>
2         | 488     | <datetime>
2         | 8       | <datetime>
4         | 384332  | <datetime>
3         | 44632   | <datetime>
1         | 6732    | <datetime>
3         | 162     | <datetime>

Example query:

SELECT
    $__time(created_at),
    sum(bits),
    attribute
FROM
    table
WHERE
    $__timeFilter(created_at)
GROUP BY created_at, attribute
ORDER BY created_at;

and attribute has distinct values (1, 2, 3, 4) so I get 4 different series, each showing data for specific attribute’s value using some kind of similar query.

Is there a way to do that?


Solution

  • you would want to group based on attribute, like you are doing in the example.

    The exact query you would need is something like this:

    SELECT
        $__time(created_at),
        attribute as metric,
        sum(bits)        
    FROM
        table
    WHERE
        $__timeFilter(created_at)
    GROUP BY created_at, attribute
    ORDER BY created_at;
    

    by giving the 'metric' alias to attribute, it will be picked up as the name of the individual timeseries and the grouping should take care of the rest