Hint and exampleShowHide
Compare each row with the following rows using LEAD (or self joins on consecutive ids) and keep the values that repeat in all of them.
Example: readings(id, status) — statuses seen at least 3 times in a row
id | status
1 | ok
2 | down
3 | down
4 | down
5 | ok
SELECT DISTINCT status
FROM (
SELECT status,
LEAD(status, 1) OVER (ORDER BY id) AS next1,
LEAD(status, 2) OVER (ORDER BY id) AS next2
FROM readings
) t
WHERE status = next1 AND status = next2; -- returns down
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) |