Search code examples
sqldatabasepostgresqlaggregate-functionswindow-functions

Postgresql cumulative sum Last 3 days


I have this data and I want to compute a rolling 3-day sum like below.

Note: Missing date has to be considered. So isn't just the last 3 rows, but 3 solar days.

enter image description here enter image description here

I tried with a window function but it's not working:

SELECT
    date,
    SUM(clicks) OVER (ORDER BY DATE ASC ROWS BETWEEN DATE - INTERVAL '3 day' AND date)
FROM table

Solution

  • Upper bound should be current row and range:

    SELECT
        date,
        SUM(clicks) OVER (ORDER BY DATE ASC range BETWEEN INTERVAL '3 day' PRECEDING AND CURRENT ROW)
    FROM table