[LeetCode]-DataBase-Consecutive Numbers

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.

需求:找出所有连续出现的数字

CREATE TABLE Logs(
Id TINYINT UNSIGNED,
Num INT UNSIGNED
)ENGINE=MyISAM;

 

-- 思路和Rank Scores类似
-- 执行结果中的rank列将Num转化为从1开始递增的序号,但序号只在Num出现变化时增加,
-- 连续出现的相同数字序号也相同,只需要统计3次或以上的记录
SELECT DISTINCT t2.Num
FROM(
SELECT t1.Num,t1.Rank
FROM(
SELECT l.Num,@curRank:=@curRank+IF(@prevValue=l.Num, 0, 1) 'Rank',@prevValue:=l.Num
FROM Logs l,(SELECT @curRank:=0) c,(SELECT @prevValue:=NULL) p
)t1
)t2
GROUP BY t2.Rank
HAVING COUNT(t2.Rank)>=3

posted @ 2016-03-22 15:53  练子  阅读(119)  评论(0编辑  收藏  举报