01 / 21

Running Totals &
Moving Averages

Master SQL window functions to compute cumulative sums and sliding averages: essential tools for time-series analysis and business reporting.

SQL

What Is a Running Total?

A running total (also called a cumulative sum) is the sum of all values from the first row up to and including the current row, when rows are ordered by some criterion like date.

Day Sales 1 100 2 150 3 200 4 120 Day Running 1 100 2 250 3 450 4 570
\(100+150+200+120 = 570\)

What Is a Moving Average?

A moving average (also called a rolling average) computes the mean of a fixed-size window of rows surrounding the current row. It smooths out short-term fluctuations to reveal trends.

Day Sales Raw Data 3-Day Avg window of 3

Why Running Totals & Averages Matter

★ Financial Reporting
Track year-to-date revenue, cumulative expenses, or account balances that grow over time.
★ Trend Detection
Smooth noisy data to see if sales are truly rising or falling, not just bouncing day to day.
★ Dashboards & KPIs
Power real-time dashboards showing progress toward quarterly goals or rolling performance.

The Window Function Pattern

Every running total and moving average in SQL follows the same structure: an aggregate function paired with an OVER clause that defines the window.

SUM(column) OVER ( PARTITION BY group_col ORDER BY sort_col ROWS BETWEEN frame_start AND frame_end )
PARTITION BY
Resets the window for each group (optional). Like a "GROUP BY" that doesn't collapse rows.
ORDER BY
Defines the logical row order. Essential: without it, "running" has no direction.
ROWS BETWEEN
Sets which rows the aggregate includes. This is the frame specification.

Running Total: The Frame Clause

For a running total, you want every row from the start of the partition up to the current row:

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
Row 1 Row 2 Row 3 Current Row 5 UNBOUNDED PRECEDING ... CURRENT ROW not included

Moving Average: The Sliding Frame

For a 3-row moving average, you want a fixed-width window that slides along with the current row:

ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
Row 1 Row 2 Row 3 Current Row 5 2 PRECEDING ... CURRENT ROW outside outside

Running Total vs Moving Average

Running Total Moving Average
Aggregate SUM() AVG()
Frame start UNBOUNDED PRECEDING N PRECEDING
Frame end CURRENT ROW CURRENT ROW
Window grows? Yes: expands each row No: fixed width, slides
Result trend Always non-decreasing (for positive values) Smoothed version of data
Use case YTD revenue, account balance 7-day trend, seasonal smoothing

How to Write the Query

1
SELECT the columns you need, including the one you want to aggregate (e.g., amount).
2
Choose your aggregate: SUM for running totals, AVG for moving averages.
3
Write the OVER clause with ORDER BY on your date/sequence column.
4
Specify the frame: UNBOUNDED PRECEDING for running totals, or N PRECEDING for moving averages.
5
Add PARTITION BY if you need separate calculations per group (e.g., per store, per product).

Example 1: Running Total of Sales

Given a table daily_sales with columns sale_date and amount, compute the cumulative revenue:

SELECT sale_date, amount, SUM(amount) OVER ( ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total FROM daily_sales;

Example 2: 3-Day Moving Average

Smooth out daily fluctuations by averaging the current day and the two preceding days:

SELECT sale_date, amount, AVG(amount) OVER ( ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS moving_avg_3d FROM daily_sales;

Example 3: Partitioned Running Total

If you have multiple stores, you probably want a separate running total for each one:

SELECT store_id, sale_date, amount, SUM(amount) OVER ( PARTITION BY store_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS store_running_total FROM daily_sales ORDER BY store_id, sale_date;

ROWS vs RANGE: A Key Distinction

ROWS
Counts physical positions in the result set. "2 PRECEDING" means exactly 2 rows before, regardless of values.
RANGE
Counts by value proximity. Rows with the same ORDER BY value are treated as peers and grouped together.

The Default Frame Trap

What happens if you write a window function without specifying ROWS BETWEEN?

-- No frame clause specified! SUM(amount) OVER (ORDER BY sale_date)
1
The SQL standard default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
2
For running totals with unique dates, this works fine: same result as ROWS.
3
For moving averages or when dates have duplicates, RANGE groups ties together, giving unexpected averages.

Common Mistakes to Avoid

✕ Missing ORDER BY
Without ORDER BY in the OVER clause, there is no defined sequence: the "running" total becomes non-deterministic.
✕ Off-by-One Frame
For a 7-day moving average, write 6 PRECEDING (not 7). The current row is already included, so \(6 + 1 = 7\).
✕ Forgetting PARTITION BY
If your data has multiple groups (stores, users), omitting PARTITION BY mixes all groups into one running total.

Quick Reference Cheat Sheet

Goal SQL Pattern
Running Total SUM(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
3-Row Moving Avg AVG(col) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
7-Row Moving Avg AVG(col) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
Per-Group Running Total SUM(col) OVER (PARTITION BY group ORDER BY date ROWS ...)
Running Count COUNT(*) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

Question 1 of 5

Which frame clause produces a running total?

Question 2 of 5

To compute a 5-day moving average, how many rows should you specify as PRECEDING?

Question 3 of 5

What does PARTITION BY do in a window function?

Question 4 of 5

What potential problem does this query have?

Question 5 of 5

Given daily sales of 10, 20, 30, 40 on four consecutive days, what is the running total on Day 3?