Hint and exampleShowHide
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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | Concept | Easy | Read the answer to What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | |||
| 2 | Rank Scores | LeetCode | Medium | Solve Rank Scores on LeetCode (opens in a new tab) | |||
| 3 | Consecutive Numbers | LeetCode | Medium | Solve Consecutive Numbers on LeetCode (opens in a new tab) | |||
| 4 | Last Person to Fit in the Bus | LeetCode | Medium | Solve Last Person to Fit in the Bus on LeetCode (opens in a new tab) | |||
| 5 | Restaurant Growth | LeetCode | Medium | Solve Restaurant Growth on LeetCode (opens in a new tab) | |||
| 6 | Department Top Three Salaries | LeetCode | Hard | Solve Department Top Three Salaries on LeetCode (opens in a new tab) |