As asked
You have a table of daily sales with columns date and amount. Write a SQL query that returns, for each date, the cumulative total amount since the beginning of the dataset and the 7-day moving average of amount.
Sample answer outline
The cumulative total uses SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). The 7-day moving average uses AVG(amount) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). A strong answer notes that ROWS BETWEEN is preferred over RANGE BETWEEN to avoid unexpected behavior with duplicate dates, and that the first 6 rows will have a moving average over fewer than 7 days.
Reference implementation (sql)
-- daily_sales(date DATE, amount NUMERIC)
SELECT
date,
amount,
SUM(amount) OVER (
ORDER BY date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_total,
AVG(amount) OVER (
ORDER BY date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM daily_sales
ORDER BY date;Expect these follow-ups
- How would you handle gaps in the date series where no sales were recorded?
- What changes if you need the 7-day moving average to always average exactly 7 days, filling missing days with zero?