SQL
Calculate a Running Total Using Window Functions
Compute cumulative sums over a sorted dataset using SQL window functions, perfect for tracking balances, scores, or inventory trends efficiently.
SELECT
order_date,
order_id,
order_total,
SUM(order_total) OVER (ORDER BY order_date ASC, order_id ASC) AS running_total
FROM
orders
ORDER BY
order_date ASC, order_id ASC;
How it works: This query calculates a running total (cumulative sum) of `order_total` for each row, ordered by `order_date` and then `order_id`. The `SUM() OVER (ORDER BY ...)` syntax is a window function that computes an aggregate value for a set of rows related to the current row, without grouping them into a single output row. The `ORDER BY` clause within the `OVER()` specifies the order in which the sum accumulates, creating a cumulative effect.