Window Function for Moving Average
Beginner Mode
Objective
Given a table sales with columns sale_date (in YYYY-MM-DD format) and amount, write an SQL query to compute the 7-day moving average of amount for each sale_date. The moving average should include the current day and the six preceding days. Round the moving average to two decimal places.
Additional information
- The output should include the columns
sale_date,amount, andmoving_average. - Order the results by
sale_datein ascending order. - Utilize appropriate SQL window functions to efficiently calculate the moving average.
- Assume that there are no duplicate
sale_dateentries and thatsale_datevalues are consecutive without gaps.
Examples
Example 1:
Output:
Input:
| sales | |
|---|---|
| amount | sale_date |
| 100 | 2023-01-01 |
| 150 | 2023-01-02 |
| 200 | 2023-01-03 |
| 120 | 2023-01-04 |
| 180 | 2023-01-05 |
| 160 | 2023-01-06 |
| 140 | 2023-01-07 |
| 190 | 2023-01-08 |
| 170 | 2023-01-09 |
| amount | moving_average | sale_date |
|---|---|---|
| 100 | 100 | 2023-01-01 |
| 150 | 125 | 2023-01-02 |
| 200 | 150 | 2023-01-03 |
| 120 | 142.5 | 2023-01-04 |
| 180 | 150 | 2023-01-05 |
| 160 | 151.67 | 2023-01-06 |
| 140 | 150 | 2023-01-07 |
| 190 | 162.86 | 2023-01-08 |
| 170 | 165.71 | 2023-01-09 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
DeutscheBank