Running Totals & Moving Averages
Compute cumulative sums and rolling averages with frame clauses for time-series SQL.
In plain words
A running total adds as it goes down the rows; a moving average averages the last few rows, sliding forward each row.
Think of it like…
A bank statement's running balance: each line shows the total up to that row. A moving average is like looking at the last seven days of the weather chart through a sliding window, smoothing out daily spikes.
Where you’ve seen it
A demand-forecasting dataset needs, for each store and day, the average sales of the previous 7 days, not including today. The query computes AVG(units) OVER (PARTITION BY store_id ORDER BY day ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) on a table with one row per store per day (built with a calendar spine so no day is missing). Excluding the current row prevents the feature from containing the very value being predicted, and the spine makes 7 rows equal 7 days.
Words you’ll hear
- Frame clause
- ROWS/RANGE BETWEEN start AND end: which rows around the current one are included.
- UNBOUNDED PRECEDING
- From the first row of the partition.
- N PRECEDING … 1 PRECEDING
- The previous N rows, excluding the current row.
- Default frame
- With ORDER BY and no frame: RANGE UNBOUNDED PRECEDING to CURRENT ROW (ties are peers).
Visual diagram
Theory & deep dive
Frames: ROWS, RANGE and the default trap
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW includes the current row and the 6 rows before it in the ordering, which is 7 days only if every day has exactly one row. RANGE frames are based on values: RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW includes all rows within 6 days of the current date, handling gaps and duplicates by date (supported in PostgreSQL 11+, MySQL 8 and others, with syntax varying). A common fix is to build a date spine and aggregate to one row per entity per day first.
The default frame when you write SUM(x) OVER (ORDER BY day) is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats rows with the same day as peers and gives them the same running total. For per-row cumulative sums with ties, use ROWS and a unique ORDER BY. Without ORDER BY the frame is the whole partition (a total, not a running total).
SUM(amount) OVER (PARTITION BY customer_id, date_trunc('year', order_date) ORDER BY order_date, order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) restarts each calendar year and breaks ties with the order id.
Time-series features without leakage, and pandas equivalents
For prediction features, use windows that end before the prediction point: ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING for "the previous 28 days excluding today". Including the current row's value when the target is that same value leaks the answer. Compute features at the grain of the prediction (entity-day) and check that the first rows, where the window is short, are handled (return NULL when fewer than N rows exist using CASE WHEN COUNT(*) OVER (...) = N THEN AVG(...) END, or add a window_size feature).
pandas equivalents: df.groupby("store")["units"].transform(lambda s: s.shift(1).rolling(7, min_periods=7).mean()) for a past-only 7-day mean, .cumsum() for running totals, and rolling("7D", on="day") for time-based windows on a datetime index. Moving averages smooth noise but lag the signal; exponentially weighted versions (ewm) react faster. Validate on a few entities by hand and compare SQL and pandas results on a sample.
CASE WHEN COUNT(*) OVER w = 28 THEN AVG(units) OVER w END AS units_avg_28d with WINDOW w AS (PARTITION BY store_id ORDER BY day ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING) returns NULL until 28 past days exist, instead of silently averaging fewer days.
How it works, step by step
Step 1 of 41. Build one row per entity per period
Aggregate to daily rows and use a calendar spine so missing days exist as zeros.
- Then
- ROWS = days
When to use it & trade-offs
What it is
Running totals (cumulative sums) and moving averages (rolling windows) are windowed aggregates: SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). The frame clause (ROWS or RANGE, with start and end) controls which neighbouring rows each calculation sees. They create time-series features (7-day averages, year-to-date spend) directly in the warehouse.
Why it matters: Rolling statistics are the backbone of forecasting and behavioural features, and they're easy to get subtly wrong: a default frame that treats tied dates as peers, a 7-row window that isn't 7 days when days are missing, or a window that includes the current day's outcome. Doing them in SQL avoids loading raw events into pandas, but only if you understand frames and leakage.
When to reach for it
- Rolling-sales and behaviour features
- Cumulative spend and year-to-date metrics
- Smoothing noisy daily series for charts
When to avoid or be careful
- Including the current row in predictive features
- Row-based windows over data with missing days
- Relying on the default frame when ties exist
Windowed aggregates
Strengths: Simple, linear cost.
Watch out: Ties and gaps need care.
Strengths: Predictable window size.
Watch out: Wrong when days are missing.
Strengths: Windows measured in time, not rows.
Watch out: Syntax varies by database.
Interview signals & numbers to know
When this topic comes up
- “Create a 7-day rolling average feature”
- “Running total with duplicate dates”
- “My feature includes the target”
- ROWS vs RANGE
- Time-series features in SQL
Benchmarks & rules of thumb
- 7 PRECEDING … 1 PRECEDING
- the previous 7 rows, excluding the current
- RANGE … CURRENT ROW
- default frame with ORDER BY
- 28
- a common window for monthly seasonality features
Common mistakes & follow-ups
Common interview mistakes
- Using ROWS BETWEEN 6 PRECEDING AND CURRENT ROW on data with missing days and calling it a 7-day average.
- Including today's value in a feature used to predict today's value.
- Averaging only 3 days for new stores in the first week without flagging it.
Likely interviewer follow-ups
- What's the difference between ROWS and RANGE frames?
- How do you avoid leakage in rolling features?
- How would you compute a 7-day moving average in pandas?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Running Totals & Moving Averages with data science interview Q&A and hands-on practice.