Running total of revenue
Task
sales has one row per sale. Return one row per day with that day's revenue and the running total up to and including that day, ordered by day. Columns: day, revenue, running_total.
Order matters: sort your rows as asked. Column names do not have to match. SQLite dialect.
Tables
sales
day TEXT, amount INTEGER
| day | amount |
|---|---|
| 2026-03-01 | 100 |
| 2026-03-01 | 50 |
| 2026-03-02 | 80 |
| 2026-03-03 | 120 |
| 2026-03-03 | 30 |
| 2026-03-04 | 40 |
- First aggregate to one row per day with GROUP BY.
- A window function can wrap an aggregate: SUM(SUM(amount)) OVER (ORDER BY day).
Expected output
| day | revenue | running_total |
|---|---|---|
| 2026-03-01 | 150 | 150 |
| 2026-03-02 | 80 | 230 |
| 2026-03-03 | 150 | 380 |
| 2026-03-04 | 40 | 420 |
Show solution
SELECT day,
SUM(amount) AS revenue,
SUM(SUM(amount)) OVER (ORDER BY day) AS running_total
FROM sales
GROUP BY day
ORDER BY day;Window functions run after GROUP BY, so SUM(SUM(amount)) OVER (ORDER BY day) adds up the daily totals. Without grouping first you get one row per sale, and tied days share the same running total.
Why this works
Window functions run after GROUP BY, so SUM(SUM(amount)) OVER (ORDER BY day) adds up the daily totals. Without grouping first you get one row per sale, and tied days share the same running total.
The full explanation, with more examples, is in the question Running total of revenue.