SQL
Calculate Running Totals Using SQL Window Functions
Master calculating cumulative sums or running totals in SQL with powerful window functions. Ideal for financial reporting, trend analysis, and tracking progress over time.
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM
sales
ORDER BY
order_date;
How it works: This query uses a window function (`SUM() OVER (...)`) to calculate a running total. The `OVER` clause defines a 'window' of rows related to the current row. `ORDER BY order_date` specifies the order within the window, and `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` ensures the sum includes all preceding rows up to the current one. This is highly useful for financial tracking, cumulative statistics, or historical trend analysis.