SQL
Calculate Running Totals in SQL with Window Functions
Discover how to use SQL window functions, specifically SUM() OVER(), to compute running totals or cumulative sums, valuable for financial reporting and analytics.
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM daily_sales
ORDER BY order_date;
How it works: Window functions perform calculations across a set of table rows that are related to the current row. Unlike aggregate functions, they do not collapse rows into a single output row. SUM() OVER (ORDER BY order_date) calculates a running total, where each row shows the sum of the 'amount' for that day and all preceding days, ordered by `order_date`. This is excellent for trend analysis.