編寫一個SQL查詢,查找至少連續出現三次的全部數字。spa
建立表和數據:3d
Create table If Not Exists Logs (Id int,Num int); Truncate table Logs; insert into Logs (Id, Num) values ('1','1'); insert into Logs (Id, Num) values ('2','1'); insert into Logs (Id, Num) values ('3', '1'); insert into Logs (Id, Num) values ('4','2'); insert into Logs (Id, Num) values ('5','1'); insert into Logs (Id, Num) values ('6','2'); insert into Logs (Id, Num) values ('7','2');
解法:code
1.題目暗示,每行的id是連續的。所以,表三次自鏈接,將連續三行且數字都相等行選出來。blog
SELECT distinct L1.num AS ConsecutiveNums FROM Logs AS L1 JOIN Logs AS L2 ON (L1.num = L2.num AND L1.id + 1 = L2.id) JOIN Logs AS L3 ON (L2.num = L3.num AND L2.id + 1 = L3.id)
2.拋開id。僅從行數據考慮,須要用戶變量記錄前一行數據。當前行數據與前一行數據比較是否相同。table
定義兩個用戶變量:class
@pre : 前一行數據變量
@dcnt :與前一行數據連續相同的個數im
初始化@pre和@dcnt,定義爲一張表:(SELECT @pre:= NULL,@dcnt:=0) AS b數據
Logs與b叉積,計算出與每行數字連續相同的數字個數。查詢
與前一行數據比較的邏輯爲:
@dcnt:= IF(@pre=t.Num, @dcnt+1, 1)
@pre與t.Num : 前一行數據與當前行相同。
若是相同,@dcnt+1,不然@dcnt=1。
這些結果造成一張新表:a(Num,cnt,USELESS)。
最終只要從a中取出cnt大於等於3的行。
SELECT DISTINCT a.Num AS ConsecutiveNums FROM ( SELECT l.Num, (@dcnt:= IF(@pre=l.Num, @dcnt+1, 1)) AS cnt, @pre:=l.NumFROM LOGS as l,(SELECT @pre:= NULL,@dcnt:=0) AS b ) AS a WHERE a.cnt >= 3;