SQL
Calculate Running Totals or Cumulative Sums with Window Functions
Discover how to compute running totals or cumulative sums in SQL using window functions like SUM() OVER (ORDER BY ...) for financial and analytical reports.
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total_amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS customer_running_total
FROM
orders
ORDER BY
order_date;
How it works: This SQL snippet demonstrates how to calculate running totals (or cumulative sums) using window functions. The `SUM(amount) OVER (ORDER BY order_date)` expression computes a cumulative sum of `amount` values, ordered by `order_date`, for all rows up to the current row. This is useful for tracking progressive totals over time. The second `SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date)` example shows how to calculate a running total *per customer*, restarting the sum for each new `customer_id`. This pattern is invaluable for financial analysis, sales tracking, and various other time-series data reports.