MOVING AVERAGES
Moving averages are useful metrics to gauge the trend of performance of a business and economic metrics. Some
example can be average weekly or monthly sales. If you are using SQL in a business context or broadly in
analytics, you will likely need to compute moving averages at some point.
In the query below, I demonstrate how to compute Moving Average using window function syntax.
SELECT
row_number() OVER() as row_num,
order_date,
total_amount,
AVG(total_amount) OVER(ORDER BY order_date ASC ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS mv_avg,
CASE WHEN row_number() over() < 7 then NULL
ELSE AVG(total_amount) OVER(ORDER BY order_date ASC ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
END AS mv_avg_offset
FROM orders
WHERE order_date IS NOT NULL
LIMIT 20;
As we have seen with Moving Totals, we can use the ROWS syntax to specify our window for moving averages to get
the moving average window we need. A useful detail to remember is that moving averages will be computed as long
as the number of rows preceding the current row exists. That is, if you are computing the moving average for a
7-day window, it is only the 7th row and beyond that will have accurate 7-day averages. The prior rows will have
averages by the window as the number of rows before them.