I have a table
datetime | value |
---|---|
2022-10-21 11:23:00 | 1 |
2022-10-22 12:12:00 | 2 |
2022-10-23 13:43:00 | 0 |
2022-10-24 14:01:00 | 5 |
2022-10-25 10:23:00 | 2 |
and I would like to get a result like this (aggregate each 3 days), gaps are possible
datetime | value |
---|---|
2022-10-21 – 2022-10-23 | 3 |
2022-10-24 – 2022-10-25 | 7 |
How can I do that?
3
Answers
lag
can be used to find alldatetime
s that constitute the start of a day range and then in a recursivecte
, the subsquentdatetime
s in its range can be joined onto it. Additionally, thecte
tracks the count of the day interval, producing anid
which can be used to separate day ranges into groups of three:See fiddle for results on both the sample and a larger set of test rows.
Test
http://sqlfiddle.com/#!17/1cee2/58
You could select row number for each row, then apply aggregate SUM function on group of each 3 rows.
You could try it here: https://onecompiler.com/postgresql/3yv74qc4p