Moving Averages: The Secret to Smooth Charts
Welcome to **Day 66**. Today we're making dirty data look clean.
The Problem: The "Zig-Zag" Chart
If you track daily sales, your chart will likely jump up and down. Weekend sales are high, Mondays are low. It's hard to see the **trend**.
A **Moving Average** (or Rolling Average) smooths this out by averaging the last few days of data for every point on the chart.
The Syntax: ROWS BETWEEN
SELECT
sale_date,
revenue,
AVG(revenue) OVER(
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) as seven_day_moving_avg
FROM daily_sales;
How it works
This tells SQL: "For every row, look at the 6 rows before it and the current row (total of 7), and calculate their average."
Why it's useful
Your Task for Today
Calculate a 3-day moving average for your hypothetical revenue data.
*Day 67: Window Frame Specification (ROWS vs RANGE).*