SELECT grid.t5
,min(t."time") AS min_time
-- ,array_agg(extract(min FROM t."time")) AS 'players_on' -- optional
,avg(t.players) AS avg_players
,avg(t.servers) AS avg_servers
FROM (
SELECT generate_series(min("time")
,max("time"), interval '5 min') AS t5
FROM tbl
) grid
LEFT JOIN tbl t ON t."time" >= grid.t5
AND t."time" < grid.t5 + interval '5 min'
GROUP BY grid.t5
ORDER BY grid.t5;
Explain
The subquery
grid
produces one row for every 5 minutes from the minimum to the maximum of "time"
in your table.LEFT JOIN back to the table slicing data in 5-min intervals. Carefully include lower border and exclude upper border.
To drop 5-min-slots where nothing happened, use
JOIN
in place ofLEFT JOIN
.To have your grid-times start at 0:00, 5:00 etc, round down the
min("time")
ingenerate_series()
.
More explanation in these related answers:
Group by data intervals
PostgreSQL: running count of rows for a query 'by minute'
Aside: I wouldn't use time
as identifier. It's a reserved word in standard SQL and a function / type name in Postgres.