Window functions
Moving aggregates and window frames
Average each product with its two immediate predecessors.
Lesson 63 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. Average each product with its two immediate predecessors.
Run the example
sql
SELECT TOP (5) ProductID, ListPrice,
AVG(ListPrice) OVER (ORDER BY ProductID
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ThreeProductAverage
FROM dbo.Products
ORDER BY ProductID;Read it step by step
- The frame includes the current product and up to two preceding ProductIDs.
- At the start there are fewer than three available rows, so AVG uses the available rows.
- TOP affects the display after the window calculation.
Check the result
| ProductID | ListPrice | ThreeProductAverage |
|---|---|---|
| 1 | 39.00 | 39.000000 |
| 2 | 129.00 | 84.000000 |
| 3 | 79.00 | 82.333333 |
| 4 | 8.50 | 72.166666 |
| 5 | 12.00 | 33.166666 |
The moving average includes at most three rows and uses the decimal output scale of AVG.
Practice
Compute a moving sum of ListPrice over the current product and one predecessor for Products 1–5.
Check your answer and expected result
Reveal answer
sql
SELECT TOP (5) ProductID, ListPrice,
SUM(ListPrice) OVER (ORDER BY ProductID
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS TwoProductSum
FROM dbo.Products
ORDER BY ProductID;| ProductID | ListPrice | TwoProductSum |
|---|---|---|
| 1 | 39.00 | 39.00 |
| 2 | 129.00 | 168.00 |
| 3 | 79.00 | 208.00 |
| 4 | 8.50 | 87.50 |
| 5 | 12.00 | 20.50 |
Product 1 uses only its own price; later rows include the previous product too.
Your progress
Reveal the check answer or reach the end to complete this lesson.