Mid
Window Functions
SQL & Databases
How do you compute a running total in SQL Server?
Short answer: Use SUM(Amount) OVER (ORDER BY OrderDate ROWS UNBOUNDED PRECEDING). Prefer ROWS over RANGE when you want physical cumulative sums with ties on the order key.
Sample solution
T-SQL
SELECT OrderId, OrderDate, Amount,
SUM(Amount) OVER (
ORDER BY OrderDate, OrderId
ROWS UNBOUNDED PRECEDING
) AS RunningTotal
FROM Orders;
Mention PARTITION BY CustomerId for per-customer running totals.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png