Q37: How do you calculate a Running Total (Cumulative Sum) in SQL?

Difficulty:MediumTopic:Practical SQL

Calculate a running total by using the SUM() aggregate window function with an explicit ORDER BY clause.

Calculating Running Totals Partitioned by Year
SELECT 
    transaction_date,
    amount,
    SUM(amount) OVER (
        ORDER BY transaction_date 
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM daily_deposits;
💡 The frame clause accumulates values from the start of the set through the current row.
Key Takeaways
  • Use SUM() OVER(ORDER BY col) to calculate cumulative running totals efficiently.
  • Frame specifications refine calculations for precise window ranges.