Skip to content
We areTOP 1%

Restaurant Growth

MediumLeetCodeSQL: Window Functions
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

Reduce the data to one row per day first, then use a frame such as ROWS BETWEEN 6 PRECEDING AND CURRENT ROW for a moving sum or average, and skip the days that lack a full window.

Example: visits(day, users) — 3-day moving average

day | users
1   | 10
2   | 20
3   | 30
4   | 40
SELECT day,
       AVG(users) OVER (ORDER BY day
                        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS avg_3d
FROM visits;
-- 1 | 10, 2 | 15, 3 | 20, 4 | 30
-- wrap it and keep day >= 3 to report only full 3-day windows

More in SQL: Window Functions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account