Moving Average based on Timestamps in PostgreSQL

后端 未结 3 1410
南方客
南方客 2020-12-08 16:04

I wanted to perform moving average through timestamps. I have two columns: Temperature and timestamps (time-date) and I want to perform the moving average based on every 15

3条回答
  •  佛祖请我去吃肉
    2020-12-08 16:23

    You can join your table with itself:

    select l1.id, avg( l2.Temperature )
    from l l1
    inner join l l2 
       on l2.id <= l1.id and
          l2.Timestamps + interval '15 minutes' > l1.Timestamps
    group by l1.id
    order by id
    ;
    

    Results:

    | ID |            AVG |
    -----------------------
    |  1 |           5.39 |
    |  2 |          5.365 |
    |  3 | 5.296666666667 |
    |  4 |         5.3575 |
    |  5 |          5.346 |
    |  6 | 5.321666666667 |
    |  7 | 5.331428571429 |
    

    Notice: Only 'hard work' is made. You should join result with original table or append new columns to query. I don't know your final query needed. Adapt this solution or ask for more help.

提交回复
热议问题