This SQL query calculates a moving average of sales amounts over a window of the current row and the four preceding rows. It returns the sales date, the sales amount for that date, and the moving average of sales amounts within this window.
SELECT sales_date, 
       sales_amount, 
       AVG(sales_amount) OVER (ORDER BY sales_date 
                               ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) AS moving_avg
FROM sales
ORDER BY sales_date;
sales_date: Retrieves the date of the sales transaction.sales_amount: Retrieves the amount of sales for that specific date.AVG(sales_amount) OVER (ORDER BY sales_date ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) AS moving_avg: This is the window function calculating the moving average.AVG(sales_amount): This is the window function used to calculate the average of the sales amounts.OVER: Defines the window of rows for the function.
ORDER BY sales_date: Orders the rows by sales_date, which is necessary for the moving average calculation to follow the sequence of dates.ROWS BETWEEN 4 PRECEDING AND CURRENT ROW: This frame clause specifies the range of rows for each calculation.
4 PRECEDING: Includes the four rows before the current row.CURRENT ROW: Includes the current row itself.FROM sales: Specifies the table from which to retrieve the data.ORDER BY sales_date: Orders the final result set by sales_date to ensure that the moving averages are presented in chronological order.Initial State: Assume the sales table has the following data:
| sales_date | sales_amount | 
|---|---|
| 2024-01-01 | 100 | 
| 2024-01-02 | 150 | 
| 2024-01-03 | 200 | 
| 2024-01-04 | 250 | 
| 2024-01-05 | 300 | 
| 2024-01-06 | 350 | 
Processing Each Row:
2024-01-01):
2024-01-02):
2024-01-03):
2024-01-04):
2024-01-05):
2024-01-06):
Final Output:
| sales_date | sales_amount | moving_avg | 
|---|---|---|
| 2024-01-01 | 100 | 100 | 
| 2024-01-02 | 150 | 125 | 
| 2024-01-03 | 200 | 150 | 
| 2024-01-04 | 250 | 175 | 
| 2024-01-05 | 300 | 200 | 
| 2024-01-06 | 350 | 250 |