LeetCode 180. Consecutive Numbers SQL Solution
Problem
LeetCode SQL Problem
- Consecutive Numbers
Logs table
Id | Num |
---|---|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 2 |
5 | 1 |
6 | 2 |
7 | 2 |
8 | 2 |
9 | 5 |
10 | 5 |
11 | 5 |
Solution - Self Join and DISTINCT
To find all numbers that appear at least three times consecutively, we perform self join on Logs
table so we have previous number, next number, and current number all in the same row.
When the value of the current number equals to the previous number and the next number, we know this number appears at least 3 times consecutively.
We use DISTINCT
keyword to not return duplicate numbers in the output.
- MySQL
- TSQL
SELECT DISTINCT A.Num AS ConsecutiveNums
FROM Logs AS A
INNER JOIN Logs AS B ON A.Id + 1 = B.Id
INNER JOIN Logs AS C ON B.Id + 1 = C.Id
WHERE A.Num = B.Num
AND B.Num = C.Num
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |
SELECT DISTINCT A.Num AS ConsecutiveNums
FROM Logs AS A
INNER JOIN Logs AS B ON A.Id + 1 = B.Id
INNER JOIN Logs AS C ON B.Id + 1 = C.Id
WHERE A.Num = B.Num
AND B.Num = C.Num
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |
Solution - Self Join and Group By
This is the same as the self join solution discussed above, we use Group By to ensure there is no duplicate number in the output.
- MySQL
- TSQL
SELECT A.Num AS ConsecutiveNums
FROM Logs AS A
INNER JOIN Logs AS B ON A.Id + 1 = B.Id
INNER JOIN Logs AS C ON B.Id + 1 = C.Id
WHERE A.Num = B.Num
AND B.Num = C.Num
GROUP BY A.Num
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |
SELECT A.Num AS ConsecutiveNums
FROM Logs AS A
INNER JOIN Logs AS B ON A.Id + 1 = B.Id
INNER JOIN Logs AS C ON B.Id + 1 = C.Id
WHERE A.Num = B.Num
AND B.Num = C.Num
GROUP BY A.Num
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |
Solution - Lag() and Lead() Window Functions
To find all numbers that appear at least three times consecutively, we utilize Lag()
and Lead()
Windows Functions to put previous number, next number, and current number all in the same row.
When the value of the current number equals to the previous number and the next number, we know this number appears at least 3 times consecutively.
We then use DISTINCT
keyword to not return duplicate numbers in the output.
- MySQL
- TSQL
WITH ConsecutiveNumAnalysis
AS (
SELECT Id
,Num AS CurrNum
,lag(Num) OVER (
ORDER BY Id
) AS PrevNum
,lead(Num) OVER (
ORDER BY Id
) AS NextNum
FROM Logs
)
SELECT DISTINCT CurrNum AS ConsecutiveNums
FROM ConsecutiveNumAnalysis
WHERE CurrNum = PrevNum
AND CurrNum = NextNum
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |
WITH ConsecutiveNumAnalysis
AS (
SELECT Id
,Num AS CurrNum
,lag(Num) OVER (
ORDER BY Id
) AS PrevNum
,lead(Num) OVER (
ORDER BY Id
) AS NextNum
FROM Logs
)
SELECT DISTINCT CurrNum AS ConsecutiveNums
FROM ConsecutiveNumAnalysis
WHERE CurrNum = PrevNum
AND CurrNum = NextNum
Query Output
ConsecutiveNums |
---|
1 |
2 |
5 |