Skip to content
Advertisement

GROUP by data by time range in postgresql

I want to GROUP by data by time range. The example I have start_date and end_date, and I want the separate range between start_date and end_date on 25 range and get sum value from 1 to 25.

Simple presentation of my table:

select * from t1
where time between start_date and end_date

table t1 have:

time 2019-10-01 value 50
time 2019-10-01 value 50
time 2019-10-02 value 50
time 2019-10-02 value 50
time 2019-10-02 value 50
time 2019-10-02 value 50
time 2019-10-03 value 50
time 2019-10-04 value 50
time 2019-10-05 value 50
time 2019-10-05 value 50
time 2019-10-05 value 50

start_date 2019-10-01
end_date   2019-10-25

generate_series function to separate on

2019-10-01
2019-10-02
2019-10-03
2019-10-04
2019-10-05
2019-10-06 
2019-10-07 
2019-10-07 
2019-10-07 
2019-10-08 
2019-10-09 
2019-10-10 
2019-10-11 
2019-10-12 
2019-10-13 
2019-10-14 
2019-10-15 
2019-10-16 
2019-10-17 
2019-10-18 
2019-10-19 
2019-10-20 
2019-10-21 
2019-10-22 
2019-10-23 
2019-10-24 
2019-10-25

and sum by how this 25

for 2019-10-01 to have value 100 for 2019-10-02 to have value 400

Advertisement

Answer

I am going to recommend a lateral join:

select d.dt, t.total_value
from generate_series(date '2019-10-01', date '2019-10-25', interval '1' day
                    ) d(dt) left join lateral
      (select coalesce(sum(value), 0) as total_value
       from t
       where t.time >= d.dt and
             t.time < d.dt + interval '1' day
      ) t
      on true;

A lateral join can have better performance than overall aggregation, particularly with an index on (time, value).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement