SQL Question: 7-Day Moving Average
📄 Table: daily_sales
sale_date | sales_amount |
---|---|
2025-06-01 | 100 |
2025-06-02 | 120 |
2025-06-03 | 130 |
2025-06-04 | 110 |
2025-06-05 | 150 |
2025-06-06 | 140 |
2025-06-07 | 160 |
2025-06-08 | 170 |
2025-06-09 | 180 |
❓ Question:
Write an SQL query to calculate the 7-day moving average of sales_amount
for each sale_date
.
The moving average should include the current day and the 6 previous days.
Return:
-
sale_date
-
sales_amount
-
moving_avg_7d
✅ Answer:
📊 Output:
sale_date | sales_amount | moving_avg_7d |
---|---|---|
2025-06-01 | 100 | NULL |
2025-06-02 | 120 | NULL |
2025-06-03 | 130 | NULL |
2025-06-04 | 110 | NULL |
2025-06-05 | 150 | NULL |
2025-06-06 | 140 | NULL |
2025-06-07 | 160 | 130.00 |
2025-06-08 | 170 | 140.00 |
2025-06-09 | 180 | 148.57 |
Comments
Post a Comment