SQL
Calculate Running Total or Cumulative Sum in SQL
Discover how to compute a running total or cumulative sum for a series of values, ordered by a specific column, using SQL window functions for financial, sales, and analytical reports.
SELECT
order_date,
sales_amount,
SUM(sales_amount) OVER (ORDER BY order_date ASC) AS running_total_sales
FROM
daily_sales
ORDER BY
order_date ASC;
How it works: This SQL snippet calculates a running total (cumulative sum) of `sales_amount` over time. The `SUM(sales_amount) OVER (ORDER BY order_date ASC)` is a window function that, for each row, sums the `sales_amount` of all preceding rows and the current row, based on the `order_date`. This is highly useful for tracking cumulative progress, like total sales over a period, without needing self-joins or complex subqueries.