SQL for analysis · Write code
A moving average that skips the quiet days
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
This query gives a dark store's 7-day average GMV for the ops review. The store had no orders on 3 and 6 November. What does the row for 9 November show, and is it right?
-- daily_sales(store_id, sale_date, gmv): one row per day that had orders
-- BLR-07, GMV in ₹ thousand: 1 Nov 100, 2 Nov 120, 4 Nov 110, 5 Nov 90,
-- 7 Nov 130, 8 Nov 140, 9 Nov 100
SELECT sale_date, gmv,
AVG(gmv) OVER (ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS gmv_7d_avg
FROM daily_sales
WHERE store_id = 'BLR-07'
ORDER BY sale_date;
Then
Follow-ups the interviewer asks next
- How many calendar days does that window really cover on 9 November?
- Fix it in two different ways.
- Should the days without orders count as zero or be left out? Who decides?
- The query now has to run for all stores at once. What else must change?
The answer
What a strong answer covers
ROWScounts rows, not days. On 9 November the seven rows are 1, 2, 4, 5, 7, 8 and 9 November, nine calendar days, so it shows about 112.9 (790 ÷ 7).- Fix 1: a calendar of days LEFT JOINed to the sales with
COALESCE(gmv, 0), then the sameROWSframe. 9 November becomes about 81.4 (570 ÷ 7, counting 3 and 6 November as zero). - Fix 2: a date-based frame,
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW(Postgres 11+, MySQL 8, DuckDB; not SQL Server), which averages only the days with rows from 3 to 9 November: 114.0 (570 ÷ 5). - Which is right is a business question: if the store was shut (a stock audit, a power cut), leaving those days out is fair; if it was open and sold nothing, zero is the truth. Asks the ops team and writes the rule down.
- For all stores:
PARTITION BY store_id, and a calendar crossed with the list of stores.
The red pen
Common traps
Avoid:"it says 7 days, so it's fine"; fixing it without asking what a missing day means.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.