Problem Statement
How do you compute a 7-day moving average per product using window functions?
Explanation
A moving window spans a fixed number of rows relative to the current row. For seven days, include six preceding rows plus the current row.
Partition by product to keep time series independent. Use ROWS frames for steady behavior when multiple rows share the same day stamp.
Code Solution
SolutionRead Only
SELECT product_id, day,
AVG(amount) OVER (
PARTITION BY product_id
ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS avg7
FROM daily_sales;