Aggregate values over a range of hours, every hour

前端 未结 2 1358
你的背包
你的背包 2021-02-07 18:02

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         


        
2条回答
  •  孤独总比滥情好
    2021-02-07 18:26

    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.

提交回复
热议问题