Paths Subjects Questions Quizzes Pricing Search
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.

  1. Explain precisely what the query is actually computing during and immediately after the closure, and why it doesn't reflect the zero days.
  2. Fix the query so the moving average correctly treats missing days as zero-revenue days.
  3. A colleague suggests switching from ROWS BETWEEN 6 PRECEDING AND CURRENT ROW to RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW as an alternative fix, without changing anything else about the underlying data. Would that actually fix the problem? Justify your answer precisely.

Share this question

← Back to Advanced SQL: Window Functions & CTEs practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.