SQL
Calculate a Running Total or Cumulative Sum
Compute a running total for values in a SQL table using window functions, perfect for analyzing cumulative sales, expenses, or progress over time.
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date, order_id) AS running_total
FROM
daily_sales
ORDER BY
order_date, order_id;
How it works: This query calculates a running total (cumulative sum) of `amount` for each row in the `daily_sales` table. The `SUM(...) OVER (ORDER BY order_date, order_id)` is a window function that sums the `amount` of the current row and all preceding rows based on the `order_date` and `order_id`. This is valuable for trend analysis, financial reporting, and tracking cumulative progress over a sequence of events.