24/34
Part 5 of 6 · Empty daysLearn and do

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;
dayrevenuerevenue_7d
2026-03-015050
2026-03-024595
2026-03-0370165
2026-03-040165
2026-03-050165
2026-03-060165
2026-03-070165
2026-03-080115
2026-03-0935105
2026-03-105085

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.