SQL Question: 7-Day Moving Average

 

📄 Table: daily_sales

sale_datesales_amount
2025-06-01100
2025-06-02120
2025-06-03130
2025-06-04110
2025-06-05150
2025-06-06140
2025-06-07160
2025-06-08170
2025-06-09180

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:


SELECT sale_date, sales_amount, ROUND(AVG(sales_amount) OVER ( ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ), 2) AS moving_avg_7d FROM daily_sales;

📊 Output:

sale_datesales_amountmoving_avg_7d
2025-06-01100NULL
2025-06-02120NULL
2025-06-03130NULL
2025-06-04110NULL
2025-06-05150NULL
2025-06-06140NULL
2025-06-07160130.00
2025-06-08170140.00
2025-06-09180148.57

Comments

Popular posts from this blog

sql question set 1

SCD Type 2 in MySQL/ coforge

3 days running average / capco