← All Exercises

Three-Day Moving Average with a RANGE Window

intermediatesql~20min

Background

Daily figures are noisy, so analysts smooth them. A calendar window includes only days that actually exist, which behaves differently from counting the previous two rows.

Problem

Given daily_sales with at most one row per date, return each sale date, its amount, and the average amount over that date and the two preceding calendar days, rounded to two decimals.

Input

A PostgreSQL daily_sales table with sale_date date PRIMARY KEY and amount numeric(10,2) NOT NULL; dates may have gaps.

Output

One row per sale date with sale_date, amount, and moving_avg_3d rounded to two decimals, ordered by date ascending.

Sample tests

Sample 1

Input: 2026-09-01 amount 100.00; 2026-09-02 amount 200.00; 2026-09-04 amount 300.00
Expected: 2026-09-01 | 100.00 | 100.00
2026-09-02 | 200.00 | 150.00
2026-09-04 | 300.00 | 250.00

Sample 2

Input: a separate dataset with only 2026-09-01 amount 100.00 and 2026-09-10 amount 500.00
Expected: 2026-09-01 | 100.00 | 100.00
2026-09-10 | 500.00 | 500.00

Your solution

Learning objective

Distinguish ROWS from RANGE window frames and compute date-aware rolling aggregates in PostgreSQL.