Moving Average based on Timestamps in PostgreSQL

后端 未结 3 1414
南方客
南方客 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:26

    Assuming you want to restart the rolling average after each 15 minute interval:

    select id, 
           temp,
           avg(temp) over (partition by group_nr order by time_read) as rolling_avg
    from (       
      select id, 
             temp,
             time_read, 
             interval_group,
             id - row_number() over (partition by interval_group order by time_read) as group_nr
      from (
        select id, 
               time_read, 
               'epoch'::timestamp + '900 seconds'::interval * (extract(epoch from time_read)::int4 / 900) as interval_group,
               temp
        from readings
      ) t1
    ) t2
    order by time_read;
    

    It is based on Depesz's solution to group by "time ranges":

    Here is an SQLFiddle example: http://sqlfiddle.com/#!1/0f3f0/2

提交回复
热议问题