Careeroza
Running Totals
Cumulative Sum
Example
Revenue accumulated order by order:
SELECT OrderID, OrderDate, Amount,
SUM(Amount) OVER (ORDER BY OrderDate) AS RunningTotal
FROM Orders;Result: 8 rows
| OrderID | OrderDate | Amount | RunningTotal |
|---|---|---|---|
| 101 | 2024-01-05 | 245.5 | 245.5 |
| 102 | 2024-01-12 | 89.9 | 335.4 |
| 103 | 2024-02-03 | 412 | 747.4 |
| 104 | 2024-02-18 | 56.25 | 803.65 |
| 105 | 2024-03-01 | 150 | 953.65 |
| 106 | 2024-03-09 | 320.75 | 1274.4 |
| 107 | 2024-03-22 | 27 | 1301.4 |
| 108 | 2024-04-02 | 198.4 | 1499.8 |
Window Frames
The frame decides which rows around the current row are included:
| Frame | Rows included |
|---|---|
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | from the first row to this one (running total) |
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW | this row and the two before it (3-row moving window) |
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING | the whole partition |
Example
A 3-order moving average:
SELECT OrderID, Amount,
ROUND(AVG(Amount) OVER (ORDER BY OrderDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS MovingAvg3
FROM Orders;Result: 8 rows
| OrderID | Amount | MovingAvg3 |
|---|---|---|
| 101 | 245.5 | 245.5 |
| 102 | 89.9 | 167.7 |
| 103 | 412 | 249.13 |
| 104 | 56.25 | 186.05 |
| 105 | 150 | 206.08 |
| 106 | 320.75 | 175.67 |
| 107 | 27 | 165.92 |
| 108 | 198.4 | 182.05 |
Running Total per Group
Example
A running total that restarts for each customer:
SELECT CustomerID, OrderDate, Amount,
SUM(Amount) OVER (PARTITION BY CustomerID ORDER BY OrderDate) AS CustomerRunningTotal
FROM Orders
ORDER BY CustomerID, OrderDate;Result: 8 rows
| CustomerID | OrderDate | Amount | CustomerRunningTotal |
|---|---|---|---|
| 1 | 2024-01-05 | 245.5 | 245.5 |
| 1 | 2024-02-18 | 56.25 | 301.75 |
| 2 | 2024-02-03 | 412 | 412 |
| 3 | 2024-03-09 | 320.75 | 320.75 |
| 4 | 2024-01-12 | 89.9 | 89.9 |
| 4 | 2024-03-22 | 27 | 116.9 |
| 5 | 2024-03-01 | 150 | 150 |
| 7 | 2024-04-02 | 198.4 | 198.4 |
Note: With ORDER BY but no frame, the default frame is RANGE ... CURRENT ROW, which includes all rows with the same sort value. Add ROWS explicitly when ties are possible.