Write a SQL query to find all numbers that appear at least three times consecutively.
+----+-----+ | Id | Num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+
For example, given the above Logs
table, 1
is the only number that appears consecutively for at least three times.
+-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+
题目链接:https://leetcode.com/problems/consecutive-numbers/
# Write your MySQL query statement below
#select Num as ConsecutiveNums from Logs where
#select Num, count(Id) as counter from Logs group by Num where counter >= 3
select distinct Num as ConsecutiveNums from
(select
Num,
@count := if(@prev = (@prev := Num), @count + 1, 1) as counter
from
Logs,
(select @prev := -1, @count := 1) as temp
) as result
where counter >= 3;