← All SQL interview questions
Three-day moving average of daily orders
MediumWindow FunctionsOracleWalmart
An operations dashboard smooths daily order volume with a 3-day moving average.
From daily_orders, return order_day, orders_count and moving_avg_3d (average of the current day and the two previous days, rounded to 2 decimals). Only return days for which three full days of data exist, so the first two days are excluded. Order by order_day.
Sample data
Table: daily_orders
10 row(s) · showing first 8
| order_dayDATE | orders_countINT |
|---|---|
| 2026-10-15 | 120 |
| 2026-10-16 | 135 |
| 2026-10-17 | 128 |
| 2026-10-18 | 150 |
| 2026-10-19 | 142 |
| 2026-10-20 | 160 |
| 2026-10-21 | 155 |
| 2026-10-22 | 170 |
daily_orders
- order_dayDATE
- orders_countINT
- Step 1: `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW` defines a frame of the current row plus the two before it.
- Step 2: For the first two days the frame is smaller than 3 rows; `COUNT(*)` over the same frame tells you how many rows were actually available.
- Step 3: Filtering on `days_in_window = 3` in the outer query keeps only full windows.
WITH w AS (
SELECT order_day,
orders_count,
ROUND(AVG(orders_count) OVER (
ORDER BY order_day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS moving_avg_3d,
COUNT(*) OVER (
ORDER BY order_day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS days_in_window
FROM daily_orders
)
SELECT order_day, orders_count, moving_avg_3d
FROM w
WHERE days_in_window = 3
ORDER BY order_day;More Window Functions questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program