SQL
Calculate Running Total Using Window Functions
Compute cumulative sums over a result set using SQL window functions, useful for tracking progress, historical totals, and trend analysis in 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 calculates a running total (or cumulative sum) of order amounts. The `SUM(amount) OVER (ORDER BY order_date, order_id)` is a window function that computes the sum of `amount` for all rows up to the current row, ordered by `order_date` and `order_id`. This is highly useful for financial reports, tracking progress, or analyzing trends over time without self-joins or subqueries.