diff --git a/db/src/rest/rest.go b/db/src/rest/rest.go index d31a734..7441383 100644 --- a/db/src/rest/rest.go +++ b/db/src/rest/rest.go @@ -450,18 +450,28 @@ func (g *RestGateway) getRoomHistory(c *gin.Context) { nodeFilter := buildNodeFilter(nodes) query := fmt.Sprintf(` + WITH binned AS ( + SELECT + date_bin(INTERVAL '1 minute', time)::TIMESTAMP AS time, + AVG(co2_ppm) AS co2_ppm, + AVG(temp) AS temp, + AVG(humidity) AS humidity, + MAX(window_open) AS window_open + FROM "%s" + WHERE time > now() - INTERVAL '%s' - INTERVAL '5 minutes' + AND %s + GROUP BY date_bin(INTERVAL '1 minute', time) + ) SELECT - date_bin(INTERVAL '5 minutes', time)::TIMESTAMP AS time, - ROUND(AVG(co2_ppm)) AS co2_ppm, - ROUND(AVG(temp), 2) AS temp, - ROUND(AVG(humidity), 2) AS humidity, - MAX(window_open) AS window_open - FROM "%s" - WHERE time > now() - INTERVAL '%s' - AND %s - GROUP BY date_bin(INTERVAL '5 minutes', time) + time, + ROUND(AVG(co2_ppm) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW)) AS co2_ppm, + ROUND(AVG(temp) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW), 2) AS temp, + ROUND(AVG(humidity) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW), 2) AS humidity, + window_open + FROM binned + WHERE time > now() - INTERVAL '%s' ORDER BY time ASC - `, g.measurementName, window, nodeFilter, + `, g.measurementName, window, nodeFilter, window, ) // Using context.Background() as seen in working snippet