SQL
Calculate a Running Total with SQL Window Functions
Learn how to compute cumulative sums or running totals efficiently in SQL using window functions like SUM() OVER (ORDER BY ...), useful for financial reports and time-series data.
SELECT
order_date,
order_amount,
SUM(order_amount) OVER (ORDER BY order_date) AS running_total
FROM
orders
ORDER BY
order_date;
How it works: This SQL snippet calculates a running total of `order_amount` based on the `order_date`. The `SUM() OVER (ORDER BY order_date)` window function aggregates the `order_amount` for the current row and all preceding rows, ordered by `order_date`. This is highly useful for tracking cumulative metrics over time, such as sales accumulation or budget usage, without collapsing rows like a standard `GROUP BY` would.