Premium problem61. Seven-Day Moving Spend

Hard Locked

orders(order_id, user_id, total_amount, ordered_at)

For each user and each calendar date in September 2026, return that day's spend and the total over that date plus the six dates before it.

Include the dates where a user spent nothing, but only between their first and last active date in the month. A user whose only order is on 10 September gets one row, not thirty.

Return user_id, date, daily_spend and rolling_7d_spend, ordered by user then date.

A row-based frame is correct only once the quiet days exist as rows, so the spine has to be built per user before the window is applied.

Tables

orders

order_id  user_id  total_amount  ordered_at
--------  -------  ------------  ----------
1         10       10.00         2026-09-02
2         10       5.00          2026-09-02
3         10       20.00         2026-09-08
4         10       30.00         2026-09-09
5         11       99.00         2026-09-10
6         10       7.00          2026-08-31

Expected result

user_id  date        daily_spend  rolling_7d_spend
-------  ----------  -----------  ----------------
10       2026-09-02  15.00        15.00
10       2026-09-03  0.00         15.00
10       2026-09-04  0.00         15.00
10       2026-09-05  0.00         15.00
10       2026-09-06  0.00         15.00
10       2026-09-07  0.00         15.00
10       2026-09-08  20.00        35.00
10       2026-09-09  30.00        50.00
... 1 more row(s)

Premium problem

This one's part of Premium. Unlock the full MySQL track plus every other premium problem on the site.

Write one SELECT query