Calculate a moving average
Your task
Return each sale ID and the average quantity of that sale and the previous sale, where one exists.
A bounded ROWS frame can include the current row and a fixed number of preceding rows.
Sample data
sales| id | album_id | quantity |
|---|---|---|
| 101 | 1 | 2 |
| 102 | 2 | 1 |
| 103 | 1 | 3 |
| 104 | 4 | 2 |
| 105 | 5 | 1 |
| 106 | 2 | 2 |
Expected output
| id | AVG(quantity) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) |
|---|---|
| 101 | 2 |
| 102 | 1.5 |
| 103 | 2 |
| 104 | 2.5 |
| 105 | 1.5 |
| 106 | 1.5 |
Show a hint
Use ROWS BETWEEN 1 PRECEDING AND CURRENT ROW.
Window functions guide
Keep detail rows while summarizing
GROUP BY would return one row per genre. A window aggregate with PARTITION BY leaves every album in the result and gives each row its genre's average. This makes it easy to compare a row with its peers.
SELECT title, genre, price,
AVG(price) OVER (PARTITION BY genre) AS genre_average
FROM albums;Specify the window order and frame
The ORDER BY inside OVER defines the order of calculation. ROWS defines which neighboring rows contribute. This example adds the current sale to all earlier sales by ID. The last ORDER BY controls the order shown on screen.
SELECT id, quantity,
SUM(quantity) OVER (
ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_quantity
FROM sales
ORDER BY id;Rank first, then filter
Window results are calculated too late for the same SELECT's WHERE clause. Compute a rank in a CTE, then filter the named result. ROW_NUMBER assigns one position per row. RANK gives ties the same position and may leave gaps.
WITH ranked AS (
SELECT title, genre, ROW_NUMBER() OVER (
PARTITION BY genre ORDER BY price, id
) AS position
FROM albums
)
SELECT genre, title FROM ranked WHERE position = 1;Worked solution
SELECT id,AVG(quantity) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM sales;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
