3-Day Moving Average of Sales

SQL coding challenge · Difficulty: medium · Topic: Window Functions · +100 XP

Problem

Daily sales are noisy. Smooth them with a 3-day moving average: each row averages itself and the two days before it. Early rows average fewer days, because fewer exist.

Schema — `daily_sales`

| Column | Type |
| --- | --- |
| order_date | DATE |
| sales | INT |

Example Input — `daily_sales`

| order_date | sales |
| --- | --- |
| 2024-06-01 | 100 |
| 2024-06-02 | 150 |
| 2024-06-03 | 120 |
| 2024-06-04 | 180 |
| 2024-06-05 | 200 |

Expected Output

| order_date | sales | moving_avg_3day |
| --- | --- | --- |
| 2024-06-01 | 100 | 100.00 |
| 2024-06-02 | 150 | 125.00 |
| 2024-06-03 | 120 | 123.33 |
| 2024-06-04 | 180 | 150.00 |
| 2024-06-05 | 200 | 166.67 |

Explanation

Each row averages itself and the two days before it, so the window is three rows wide once there are three rows to fill it.

Row 1 has only itself: 100 / 1 = 100.00. Row 2 averages two days: (100 + 150) / 2 = 125.00. Row 3 is the first full window: (100 + 150 + 120) / 3 = 123.33. Row 4 drops the oldest day and picks up a new one: (150 + 120 + 180) / 3 = 150.00.

The early rows averaging fewer than three days is expected, not an edge case to guard against.

Notes

What this SQL challenge teaches you

“3-Day Moving Average of Sales” is a medium-level SQL challenge focused on Window Functions. Working through it gives you hands-on practice with AVG, OVER, ROWS BETWEEN, Moving Average — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is a 3-row window.
  2. Row 1 averages 1 value, row 2 averages 2, row 3 onwards averages 3.
  3. Wrap the average in ROUND(..., 2).

How to practise it on PySpark.in

Open the challenge, write your SQL query in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related SQL challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The SQL environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated medium and covers Window Functions.

Solve this challenge free on PySpark.in