Running total with SUM() OVER
Question
List the orders by date and show each order's id, ordered_on, and a running count of orders up to and including that one.
customersid, name, country, joined_on
productsid, name, category, price
ordersid, customer_id, ordered_on, status
order_itemsorder_id, product_id, quantity
Your query
Ctrl+Enter to run
Result
Expected result
| id | ordered_on | orders_so_far |
|---|---|---|
| 1 | 2024-07-01 | 1 |
| 2 | 2024-07-03 | 2 |
| 3 | 2024-07-09 | 3 |
| 4 | 2024-07-12 | 4 |
| 5 | 2024-07-15 | 5 |
| 6 | 2024-07-20 | 6 |
| 7 | 2024-07-22 | 7 |
Hint
COUNT(*) OVER (ORDER BY ...) counts the rows from the first one up to the current row.
Show the solution
solution.sql
Run this code
SELECT id, ordered_on,
COUNT(*) OVER (ORDER BY ordered_on, id) AS orders_so_far
FROM orders
ORDER BY ordered_on, id;
Why it works
With ORDER BY inside OVER, the window grows row by row from the start, so the count goes 1, 2, 3 and so on. The same pattern with SUM(amount) gives a running total of money.
Common mistake
Ordering the window only by a column with ties (two orders on the same day) makes those rows share a count. Add a unique column such as id to the ORDER BY.