标签:
1、题目名称
Consecutive Numbers(找出连续出现的数字)
2、题目地址
https://leetcode.com/problems/consecutive-numbers/
3、题目内容
写一个SQL,查出表Logs中连续出现至少3次的数字:
+----+-----+ | Id | Num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+
比如上表中,查出的结果是1
4、初始化数据库脚本
在MySQL数据库中建立一个名为LEETCODE的数据库,用MySQL命令行中的source命令执行下面脚本:
-- 执行脚本前必须建立名为LEETCODE的DATABASE USE LEETCODE; DROP TABLE IF EXISTS Logs; CREATE TABLE Logs ( Id INT NOT NULL PRIMARY KEY, Num INT ); 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, 1); INSERT INTO Logs (Id, Num) VALUES (5, 2); INSERT INTO Logs (Id, Num) VALUES (6, 1); INSERT INTO Logs (Id, Num) VALUES (7, 2); INSERT INTO Logs (Id, Num) VALUES (8, 2); INSERT INTO Logs (Id, Num) VALUES (9, 2);
5、解题SQL
找出至少三次连续出现的数字,最简单的方法就是直接使用一套SELECT-FROM-WHERE语句一气呵成:
SELECT DISTINCT L1.Num FROM Logs L1, Logs L2, Logs L3 WHERE (L1.Id = L2.Id + 1 AND L1.Num = L2.Num) AND (L1.Id = L3.Id + 2 AND L1.Num = L3.Num)
也可以使用JOIN子句完成同样的功能:
SELECT DISTINCT L1.Num FROM Logs L1 JOIN Logs L2 ON L1.Id + 1 = L2.Id JOIN Logs L3 ON L1.Id + 2 = L3.Id WHERE L1.Num = L2.Num AND L1.Num = L3.Num ORDER BY L1.Num
上面两种方法可以用于找到至少三次连续出现的数字,如果将连续出现的数字扩展到N个,按照上面思路写出的SQL语句就会比较长。因此可以用下面这种方式来查询:
SELECT DISTINCT Num FROM ( SELECT Num, CASE WHEN @prev = Num THEN @count := @count + 1 WHEN (@prev := Num) IS NOT NULL THEN @count := 1 END CNT FROM Logs, (SELECT @prev := NULL) X ORDER BY Id ) AS A WHERE A.CNT >= 3
将最后一行的3改为N,即可用于查询至少N次连续出现的数字。
END
LeetCode:Consecutive Numbers - 找出连续出现的数字
标签:
原文地址:http://my.oschina.net/Tsybius2014/blog/494823