Skip to the page

SQL for analysis · mid

Running totals and period-over-period

Window functions give running totals, moving averages and comparisons with an earlier period. Aggregate first, fill missing days with a calendar, and know what the frame counts.

The notes

What you must know

  • Aggregate first (daily GMV in a CTE), then apply the window. Windowing raw rows is slower and usually wrong.
  • Month-to-date that restarts each month: SUM(gmv) OVER (PARTITION BY DATE_TRUNC('month', day) ORDER BY day). Without PARTITION BY the total never restarts.
  • 7-day moving average: AVG(gmv) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).
  • ROWS counts rows, not days. If a day has no row, 7 rows cover more than 7 days. Join a calendar of days and use COALESCE(gmv, 0), or use a date-based frame (RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW where the engine supports it).
  • A missing day can mean zero sales or a closed store. That is a business question: ask, then write the rule down.
  • With ORDER BY and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Equal ORDER BY values are one group, so a running total over non-unique timestamps jumps in steps.
  • Same day last week: LAG(gmv, 7) OVER (ORDER BY day), which is right only on a complete calendar. For many stores add PARTITION BY store_id and cross the calendar with the list of stores.
  • The first days have fewer than seven rows. Show them as partial or start the query 6 days earlier and filter afterwards.

The red pen

Common traps: mistake → fix

  • Mistake: A running total needs a self-join

    Fix: a window SUM with ORDER BY does it in one pass and is much faster.

  • Mistake: AVG over 7 PRECEDING rows is a 7-day average

    Fix: only if every day has exactly one row.

  • Mistake: Filling every gap with zero is always right

    Fix: a closed store is not a day of zero sales.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write a running total of daily sales.
  2. How do you restart the total every month?
  3. What is the difference between ROWS and RANGE in a window frame?
  4. Your 7-day moving average looks too high. Quiet days have no rows. What happened?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview