Calculating Running Totals with SQL
Welcome to **Day 65**. Today we build the "Cumulative Chart." How much have we earned *total* since the beginning of the year?
The Running Total Logic
Normally, `SUM()` gives you the total of all rows. But inside a window, if you add an `ORDER BY`, it becomes a **cumulative sum**.
SELECT
month,
revenue,
SUM(revenue) OVER(ORDER BY month) as running_total
FROM monthly_sales;
How it works
The `ORDER BY` inside the `OVER` clause tells SQL: "For this row, sum all rows from the beginning of the list up to the current row."
PARTITION + ORDER BY
You can even track running totals *per customer*:
SELECT
customer_id,
order_date,
amount,
SUM(amount) OVER(PARTITION BY customer_id ORDER BY order_date) as customer_cumulative_spend
FROM orders;
This is how fintech apps calculate your "Balance History" chart!
Your Task for Today
Calculate the cumulative count of new signups per day for the last month.
*Day 66: Moving Averages (The Secret to Smooth Charts).*