SQL Window Function Running Total Example
Compute running day-by-day totals without complex self-joins using SQL Window Functions.
Why this matters
Running totals show progress toward a target day by day. Window functions build them without complicated tricks.
GROUP BY Squeezes Rows Together
GROUP BY turns many rows into one. A window function keeps every row and adds a new column beside it.
In real life: A bank statement shows every transaction and the running balance beside it. GROUP BY would only show the final balance. A window function gives you both.
OVER Adds Up as It Goes
SUM(daily_amount) OVER (ORDER BY sale_date) adds up the amounts from the first day to the current row.
In real life: Your piggy bank on day 1 holds 15,000. On day 2 it holds 15,000 plus 28,000. OVER (ORDER BY date) keeps that running total for every day.
No More Self-Joins
Window functions do running totals in one line. Before them, people joined a table to itself, which was slow and hard to read.
In real life: Before OVER, you needed a complex trick to compare each row with all earlier rows. Now one short line does it, and the result is easy to read.
Your practice task
Generate a daily cumulative sales pacing report. For each day, display the sale_date, daily_amount, and calculate a progressive cumulative sum column named running_total ordered chronologically by sale date.
How to do it
- Look at the daily_sales table.
- Decide which column sets the order of the days.
- Add a column that adds up each day with all days before it.
- Press Run proof and read the checklist.
Practice it for free in the app. You get instant checks that show what you got right and what to fix. A lesson takes about two minutes and you can try as many times as you like.
Quick reference: Running Total Window Function
The gold-standard SQL pattern for tracking pacing, revenue velocity, and trajectory.
SELECT transaction_date, amount, SUM(amount) OVER (ORDER BY transaction_date) AS cumulative_amount FROM transactions;
More lessons in this course
- SQL CTE Example: Find Above-Average CustomersBreak a hard question into named steps with WITH, then compare each group to the overall average.
- SQL ROW_NUMBER PARTITION BY: Top N Per GroupUse ROW_NUMBER with PARTITION BY to find the top record inside every group.
- Choosing Columns with SELECTQuery database tables and retrieve specific columns instead of dumping unnecessary data.