I have a PostgreSQL 9.1 database with a table containing a timestamp and a measuring value
\'2012-10-25 01:00\' 2
\'2012-10-2
A window function with a custom frame makes this amazingly simple:
SELECT ts
,avg(val) OVER (ORDER BY ts
ROWS BETWEEN CURRENT ROW AND 7 FOLLOWING) AS avg_8h
FROM tbl;
Live demo on sqlfiddle.
The frame for each average is the current row plus the following 7. This assumes you have exactly one row for every hour. Your sample data seems to imply that, but you did not specify.
The way it is, avg_8h
for the final (according to ts
) 7 rows of the set is computed with fewer rows, until the value of the last row equals its own average. You did not specify how to deal with the special case.