Calculate Moving Averages with Window Frames in SQL
📖 Scenario: You work for a retail company that tracks daily sales. You want to analyze sales trends by calculating moving averages of daily sales over a 3-day window.
🎯 Goal: Create a SQL query that calculates the 3-day moving average of daily sales using window frames.
📋 What You'll Learn
Create a table called
daily_sales with columns sale_date (date) and amount (integer).Insert the exact sales data for 5 consecutive days as specified.
Define a window frame that looks at the current day and the two previous days ordered by
sale_date.Calculate the moving average of
amount over this window frame and name the result moving_avg.💡 Why This Matters
🌍 Real World
Moving averages help businesses understand trends by smoothing out daily fluctuations in sales data.
💼 Career
Data analysts and database developers often use window functions to perform advanced calculations like moving averages for reporting and decision-making.
Progress0 / 4 steps