SQL
Calculating a Running Total (Cumulative Sum) with Window Functions
Compute cumulative sums or running totals in SQL queries with precision using window functions, perfect for tracking cumulative metrics over time or categories.
SELECT
order_date,
daily_sales,
SUM(daily_sales) OVER (ORDER BY order_date) AS running_total_sales
FROM
(SELECT order_date, SUM(amount) AS daily_sales FROM orders GROUP BY order_date) AS daily_summary
ORDER BY
order_date;
How it works: This snippet calculates a running total of sales over time. It first aggregates daily sales, then applies the `SUM()` window function with an `OVER (ORDER BY order_date)` clause. This configuration ensures that the sum accumulates for each row based on the chronological order of `order_date`, providing a cumulative sales figure at each point in time without altering the number of rows.