SQL
Calculating Running Totals with Window Functions
Master SQL window functions to compute cumulative sums or running totals over a partitioned set of data, perfect for financial and sales reports.
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date, order_id) AS running_total
FROM
orders
ORDER BY
order_date, order_id;
How it works: This snippet utilizes a window function `SUM() OVER (ORDER BY ...)` to calculate a running total. For each row, it sums the 'amount' from the current row and all preceding rows within the entire result set, ordered by `order_date` and `order_id`. This is highly efficient for cumulative calculations.