Calculate a moving average over complete windows
Your task
Order receipts by sold_on then ID. Return id and avg_last_three, the average amount over the current and previous two receipts, rounded to two decimals. Output only rows with all three receipts available and preserve that order.
At the start of a running window, fewer rows may be available than the requested frame size.
Sample data
receipts| id | sold_on | amount | channel | metadata |
|---|---|---|---|---|
| 1 | 2025-01-01 | 36 | ONLINE | {"currency":"EUR","tags":["gift","jazz"]} |
| 2 | 2025-01-16 | 22 | Store | {"currency":"EUR","tags":["indie"]} |
| 3 | 2025-01-31 | 54 | online | {"currency":"EUR","tags":["returning","bundle"]} |
| 4 | 2025-03-04 | 38 | STORE | {"currency":"EUR","tags":[]} |
| 5 | 2025-04-09 | 44 | Online | {"currency":"EUR","tags":["indie"]} |
Expected output
| id | avg_last_three |
|---|---|
| 3 | 37.33 |
| 4 | 38 |
| 5 | 45.33 |
Show a hint
Use the same three-row window for COUNT and AVG in a CTE, then filter where the window count is three.
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
WITH windows AS (SELECT id,sold_on,COUNT(*) OVER recent AS n,ROUND(AVG(amount) OVER recent,2) AS avg_last_three FROM receipts WINDOW recent AS (ORDER BY sold_on,id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)) SELECT id,avg_last_three FROM windows WHERE n=3 ORDER BY sold_on,id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
