題目:
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.
解析:
首先,增加一個rank字段,記錄序號,初始值爲1,當後一個值與前一個值相等時,序號加1。之後,把所有rank值大於等於3的都檢索出來,再去重即可。代碼如下:
# Write your MySQL query statement below
SELECT DISTINCT(Num) AS ConsecutiveNums FROM
(SELECT Id,Num,
@Rank:=IF(@prevNum != Num,1,@Rank+1) AS Rank,
@prevNum:=Num
FROM Logs) t,
(SELECT @Rank:=0,@prevNum:=NULL) r
WHERE t.Rank >= 3;