Window functions
Running totals
Accumulate payment amounts in a deterministic sequence.
Lesson 62 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Accumulate payment amounts in a deterministic sequence.
Run the example
sql
SELECT TOP (5) PaymentID, Amount,
SUM(Amount) OVER (ORDER BY PaymentID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningAmount
FROM dbo.Payments
ORDER BY PaymentID;Read it step by step
- The window ORDER BY establishes PaymentID sequence.
- The ROWS frame starts at the first payment and ends at the current row.
- SUM returns a growing total while each payment row remains visible.
Check the result
| PaymentID | Amount | RunningAmount |
|---|---|---|
| 3 | 189.00 | 189.00 |
| 4 | 374.00 | 563.00 |
| 7 | 117.00 | 680.00 |
| 8 | 677.00 | 1357.00 |
| 11 | 143.00 | 1500.00 |
PaymentID is unique, so the running order is repeatable.
Practice
Compute a running sum of ListPrice by ProductID and show the first five products.
Check your answer and expected result
Reveal answer
sql
SELECT TOP (5) ProductID, ListPrice,
SUM(ListPrice) OVER (ORDER BY ProductID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningPrice
FROM dbo.Products
ORDER BY ProductID;| ProductID | ListPrice | RunningPrice |
|---|---|---|
| 1 | 39.00 | 39.00 |
| 2 | 129.00 | 168.00 |
| 3 | 79.00 | 247.00 |
| 4 | 8.50 | 255.50 |
| 5 | 12.00 | 267.50 |
Each RunningPrice includes that product and all earlier ProductIDs.
Your progress
Reveal the check answer or reach the end to complete this lesson.