Running totals and moving averages turn raw rows into trend insights. Whether you track revenue, conversions, or defect counts, window functions deliver progressive metrics without complicated self-joins.
| Type | Description |
|---|---|
| Cumulative Total | Adds values as the row order progresses. |
| Moving Average | Returns the average over the last N rows. |
| Cumulative Count / % | Calculates progressive counts or ratios. |
| ID | Region | Month | Sales |
|---|---|---|---|
| 1 | East | Jan | 1000 |
| 2 | East | Feb | 1500 |
| 3 | East | Mar | 1200 |
| 4 | East | Apr | 1800 |
| 5 | West | Jan | 2000 |
| 6 | West | Feb | 2500 |
| 7 | West | Mar | 1800 |
| 8 | West | Apr | 3000 |
SELECT
Region,
Month,
Sales,
SUM(Sales) OVER (PARTITION BY Region ORDER BY Month) AS RunningTotal
FROM Sales;
SELECT
Region,
Month,
COUNT(*) OVER (PARTITION BY Region ORDER BY Month) AS MonthCount
FROM Sales;
SELECT
Region,
Month,
Sales,
SUM(Sales) OVER (PARTITION BY Region ORDER BY Month) * 100.0 /
SUM(Sales) OVER (PARTITION BY Region) AS CumulativePercent
FROM Sales;
SELECT
Region,
Month,
Sales,
AVG(Sales) OVER (
PARTITION BY Region
ORDER BY Month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS MovingAvg3
FROM Sales;
SELECT
Region,
Month,
Sales,
SUM(Sales) OVER (
PARTITION BY Region
ORDER BY Month
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
) AS TwoMonthSum
FROM Sales;
SELECT
Region,
SaleDate,
SUM(Sales) OVER (
PARTITION BY Region
ORDER BY SaleDate
) AS RunningTotal
FROM Sales;
Track revenue or expense growth over time using running totals.
Visualize rolling averages to smooth out month-to-month spikes.
Monitor cumulative sign-ups or conversions for campaigns.
Generate cumulative pass/fail counts directly in SQL for reports.
ROWS BETWEEN) to define window size.ROWS BETWEEN defines which rows feed each calculation.”