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

OrderIDOrderDateAmountRunningTotal
1012024-01-05245.5245.5
1022024-01-1289.9335.4
1032024-02-03412747.4
1042024-02-1856.25803.65
1052024-03-01150953.65
1062024-03-09320.751274.4
1072024-03-22271301.4
1082024-04-02198.41499.8

Window Frames

The frame decides which rows around the current row are included:

FrameRows included
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWfrom the first row to this one (running total)
ROWS BETWEEN 2 PRECEDING AND CURRENT ROWthis row and the two before it (3-row moving window)
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWINGthe 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

OrderIDAmountMovingAvg3
101245.5245.5
10289.9167.7
103412249.13
10456.25186.05
105150206.08
106320.75175.67
10727165.92
108198.4182.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

CustomerIDOrderDateAmountCustomerRunningTotal
12024-01-05245.5245.5
12024-02-1856.25301.75
22024-02-03412412
32024-03-09320.75320.75
42024-01-1289.989.9
42024-03-2227116.9
52024-03-01150150
72024-04-02198.4198.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.