LEFT JOIN onto the calendar, and then a ROWS frame counts days
Now join each day's revenue onto the calendar, and fill the gaps with 0:
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-10'
), daily AS (
SELECT ordered_on, SUM(amount) AS revenue
FROM orders
GROUP BY ordered_on
)
SELECT d.day,
COALESCE(daily.revenue, 0) AS revenue,
SUM(COALESCE(daily.revenue, 0)) OVER (
ORDER BY d.day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS revenue_7d
FROM days AS d
LEFT JOIN daily ON daily.ordered_on = d.day
ORDER BY d.day;
| day | revenue | revenue_7d |
|---|---|---|
| 2026-03-01 | 50 | 50 |
| 2026-03-02 | 45 | 95 |
| 2026-03-03 | 70 | 165 |
| 2026-03-04 | 0 | 165 |
| 2026-03-05 | 0 | 165 |
| 2026-03-06 | 0 | 165 |
| 2026-03-07 | 0 | 165 |
| 2026-03-08 | 0 | 115 |
| 2026-03-09 | 35 | 105 |
| 2026-03-10 | 50 | 85 |
A LEFT JOIN keeps every row of the table on its left, here every day, and fills the right side's columns with NULL where nothing matches. COALESCE(daily.revenue, 0) returns its first argument that isn't NULL. So a day the LEFT JOIN found no revenue for gets 0 instead of NULL.
Every day has a row now, with 0 where nothing happened. So ROWS BETWEEN 6 PRECEDING AND CURRENT ROW really is seven days. On March 9 the frame holds March 3 to 9: 70, five zeros and 35, which is 105.
That's the calendar-table answer to the practice problem's follow-up about days with no bookings. For several cities, cross join the cities with the calendar first, and partition the window by city.
In the editor, write DAILY_ORDERS: every day with its order count, 0 on the empty ones.