SQL
Calculate a Running Total (Cumulative Sum) in SQL
Discover how to compute a running total or cumulative sum over a set of rows in SQL using window functions, perfect for financial reports and analytics.
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date ASC) as running_total
FROM sales_transactions
ORDER BY order_date ASC;
-- For a running total partitioned by customer:
-- SELECT
-- customer_id,
-- order_date,
-- amount,
-- SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date ASC) as customer_running_total
-- FROM sales_transactions
-- ORDER BY customer_id, order_date ASC;
How it works: This snippet shows how to calculate a running total or cumulative sum. It utilizes the `SUM()` aggregate function combined with an `OVER` clause, which defines a window of rows. `ORDER BY order_date ASC` within the `OVER` clause ensures that the sum accumulates based on the chronological order of transactions. The sum for each row includes its own `amount` plus the `amount` of all preceding rows within the defined window. The commented section demonstrates partitioning the running total by `customer_id`.