Intermediate
Open
Pro
A 7-Day Moving Average That Isn't Actually 7 Days
A dashboard shows a "7-day trailing moving average of daily revenue per store," computed with:
SELECT
store_id,
order_date,
daily_revenue,
AVG(daily_revenue) OVER (
PARTITION BY store_id
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM daily_store_revenue;
daily_store_revenue is populated by a nightly job that only inserts a
row for a store on days it had at least one sale — stores with zero
sales on a given day simply have no row for that day at all. A store
manager notices the "7-day average" looks unusually smooth and high
right after a known 4-day closure (a renovation) and asks why the
average doesn't reflect the closure at all.
- Explain precisely what the query is actually computing during and immediately after the closure, and why it doesn't reflect the zero days.
- Fix the query so the moving average correctly treats missing days as zero-revenue days.
- A colleague suggests switching from
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWtoRANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROWas an alternative fix, without changing anything else about the underlying data. Would that actually fix the problem? Justify your answer precisely.
Share this question