You have a table called Steps that tracks daily step counts for users. Write a SQL query to calculate the 3-day rolling average of steps for each user.
A 3-day rolling average for a given date is the average of step counts for that date and the 2 preceding consecutive dates. If there aren't enough preceding dates, the rolling average is not defined for that date.
Requirements:
- Calculate 3-day rolling averages ending on each date
- Round the rolling average to 2 decimal places
- Order results by
user_id, thensteps_datein ascending order - Only include dates where a 3-day rolling average can be calculated
Table Schema
| Column Name | Type | Description |
|---|---|---|
user_id
PK
|
int | User identifier |
steps_count
|
int | Number of steps taken on the date |
steps_date
PK
|
date | Date when steps were recorded |
Input & Output
| user_id | steps_count | steps_date |
|---|---|---|
| 1 | 8000 | 2023-02-01 |
| 1 | 9000 | 2023-02-02 |
| 1 | 7000 | 2023-02-03 |
| 1 | 10000 | 2023-02-04 |
| 2 | 6000 | 2023-02-01 |
| 2 | 8000 | 2023-02-02 |
| user_id | steps_date | rolling_average |
|---|---|---|
| 1 | 2023-02-01 | 8000 |
| 1 | 2023-02-02 | 8500 |
| 1 | 2023-02-03 | 8000 |
| 1 | 2023-02-04 | 8666.67 |
| 2 | 2023-02-01 | 6000 |
| 2 | 2023-02-02 | 7000 |
For user 1: The first 3-day rolling average is available on 2023-02-03, averaging days 01, 02, 03: (8000+9000+7000)/3 = 8000.00. On 2023-02-04, we average days 02, 03, 04: (9000+7000+10000)/3 = 8666.67. User 2 only has 2 days of data, so no 3-day rolling average can be calculated.
| user_id | steps_count | steps_date |
|---|---|---|
| 1 | 5000 | 2023-01-01 |
| 1 | 6000 | 2023-01-02 |
| 1 | 7000 | 2023-01-03 |
| 2 | 4000 | 2023-01-01 |
| 2 | 5000 | 2023-01-02 |
| 2 | 6000 | 2023-01-03 |
| 2 | 8000 | 2023-01-04 |
| user_id | steps_date | rolling_average |
|---|---|---|
| 1 | 2023-01-01 | 5000 |
| 1 | 2023-01-02 | 5500 |
| 1 | 2023-01-03 | 6000 |
| 2 | 2023-01-01 | 4000 |
| 2 | 2023-01-02 | 4500 |
| 2 | 2023-01-03 | 5000 |
| 2 | 2023-01-04 | 6333.33 |
Both users have enough data for rolling averages. User 1: (5000+6000+7000)/3 = 6000.00 on Jan 3rd. User 2: (4000+5000+6000)/3 = 5000.00 on Jan 3rd, and (5000+6000+8000)/3 = 6333.33 on Jan 4th.
| user_id | steps_count | steps_date |
|---|---|---|
| 3 | 12000 | 2023-03-01 |
| 3 | 15000 | 2023-03-02 |
| user_id | steps_date | rolling_average |
|---|---|---|
| 3 | 2023-03-01 | 12000 |
| 3 | 2023-03-02 | 13500 |
User 3 only has 2 days of step data, which is insufficient to calculate a 3-day rolling average. The result is empty as no rolling averages can be computed.
Constraints
-
1 ≤ user_id ≤ 1000 -
1 ≤ steps_count ≤ 100000 -
steps_dateis a valid date -
Each
(user_id, steps_date)combination appears at most once