Original title
Write a SQL query to find all numbers that appear at least three consecutive times.
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
For example, given the above Logs
table, only 1 consecutive number of at least three times.
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
Source: LeetCode
Link: https://leetcode-cn.com/problems/consecutive-numbers
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1
Methods: DISTINCT
and WHERE
statements
Consecutive identical numbers mean Id is attached, since this question is asked at least 3 consecutive times, we use Logs
and check for three consecutive identical digits.
SELECT *
FROM
Logs l1,
Logs l2,
Logs l3
WHERE
l1.Id = l2.Id - 1
AND l2.Id = l3.Id - 1
AND l1.Num = l2.Num
AND l2.Num = l3.Num
;
Then we choose any Num from the above table to get the answer we want. At the same time, we need to add keywords DISTINCT
, because if a number appears more than 3 times in a row, repeated elements will be returned.
SELECT DISTINCT
l1.Num AS ConsecutiveNums
FROM
Logs l1,
Logs l2,
Logs l3
WHERE
l1.Id = l2.Id - 1
AND l2.Id = l3.Id - 1
AND l1.Num = l2.Num
AND l2.Num = l3.Num
;
Solution 2
The window function lead()
solves perfectly
The deviation function using the window function is perfectly implemented. It can be understood like this: copy num into the two columns num1 and num2, and then move num1 up by one row as a whole, and move num2 up by two rows as a whole, as follows:
so as long as num=num1=num2 is enough.
# Write your MySQL query statement below
select distinct num as ConsecutiveNums from
(
select num,lead(num,1)over()as num1,lead(num,2)over()as num2
from logs
) as c
where c.num = c.num1 and c.num1 = c.num2
Solution 3
Use variables instead of connecting multiple tables to reduce the time and space complexity.
Pre record the value of the previous number, count, nums record the number of occurrences of the previous number
IF() expression usage
select
distinct num as ConsecutiveNums
from
(
select
num,
if(@pre=num,@count:=@count+1,@count:=1) as nums,
@pre:=num
from logs as l,
(select @pre:=null,@count:=1)as pc
) as n
where nums>=3