Example 1
Compute a 3-day rolling average of daily revenue
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW defines a frame that includes at most the current row and two rows before it in date order. Jan 1 has no preceding rows so the average is computed over just itself: 10. Jan 2 has one preceding row so the average spans [10, 20] = 15. From Jan 3 onward the full 3-row window is available: [10, 20, 30] = 20, [20, 30, 40] = 30, [30, 40, 50] = 40. Multiplying revenue * 1.0 forces floating-point division in all engines. To compute a 7-day moving average, change 2 PRECEDING to 6 PRECEDING.
CREATE TABLE daily_sales (sale_date VARCHAR(10), revenue INT);
INSERT INTO
daily_sales
VALUES
('2024-01-01', 10),
('2024-01-02', 20),
('2024-01-03', 30),
('2024-01-04', 40),
('2024-01-05', 50);SELECT
sale_date,
revenue,
AVG(revenue * 1.0) OVER (
ORDER BY
sale_date ROWS BETWEEN 2 PRECEDING
AND CURRENT ROW
) AS moving_avg_3day
FROM
daily_sales
ORDER BY
sale_date;| sale_date | revenue | moving_avg_3day |
|---|---|---|
| 2024-01-01 | 10 | 10 |
| 2024-01-02 | 20 | 15 |
| 2024-01-03 | 30 | 20 |
| 2024-01-04 | 40 | 30 |
| 2024-01-05 | 50 | 40 |
Output is identical across all supported engine versions.