๐ Question 11: Calculate a Running Total of Sales
Suppose you have a Sales table:
sale_id | sale_date | amount
--------|------------|-------
1 | 2026-01-01 | 1000
2 | 2026-01-02 | 1500
3 | 2026-01-03 | 800
4 | 2026-01-04 | 1200
โ Calculate the cumulative (running) sales amount for each day.
๐ก Approach
A running total means:
Current day's sales + all previous sales
For example:
1000
1000 + 1500 = 2500
2500 + 800 = 3300
3300 + 1200 = 4500
The easiest approach is to use the "SUM()" window function.
๐ SQL Solution
SELECT
sale_date,
amount,
SUM(amount) OVER (
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM Sales
ORDER BY sale_date;
๐ How does it work?
1๏ธโฃ "ORDER BY sale_date"
Determines the order in which the running total is calculated.
2๏ธโฃ "SUM(amount) OVER(...)"
Calculates the sum without collapsing the rows like a normal "GROUP BY".
3๏ธโฃ "UNBOUNDED PRECEDING"
Means:
Start from the first row.
4๏ธโฃ "CURRENT ROW"
Means:
Include the current row in the total.
So the calculation becomes:
Date Amount Running Total
---------- -------- -------------
Jan 01 1000 1000
Jan 02 1500 2500
Jan 03 800 3300
Jan 04 1200 4500
โ ๏ธ Interview Trap
Don't use:
GROUP BY sale_date
for a running total.
"GROUP BY" collapses rows into groups.
A window function allows us to calculate an aggregate while keeping individual rows.
Also, if multiple rows can have the same "sale_date", be careful about the ordering. A unique column such as "sale_id" may need to be included:
SUM(amount) OVER (
ORDER BY sale_date, sale_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
๐ฏ Double Tap โค๏ธ For More