连续出现的数字
连续出现的数字 - LeetCode (中国) https://leetcode-cn.com/problems/consecutive-numbers/description/
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 | +-----------------+
SELECT DISTINCT(Num) AS ConsecutiveNums FROM Logs AS L WHERE
Num = (SELECT Num FROM Logs tmp0 WHERE tmp0.Id=L.Id+1)
AND Num = (SELECT Num FROM Logs tmp0 WHERE tmp0.Id=L.Id+2);
错误答案:
SELECT Num AS ConsecutiveNums FROM (
-- 汇聚模式子值
SELECT GROUP_CONCAT(caseChk) AS toChkStr,Num FROM (
-- 构造模式
SELECT L.*,
CASE
WHEN Id=1 THEN 0
WHEN ( Id>1 AND Num = (SELECT Num FROM Logs tmp0 WHERE tmp0.Id=L.Id-1) ) THEN 0
ELSE 1
END AS caseChk
FROM Logs AS L
) AS tPartern GROUP BY Num
) AS tPertenGroup WHERE INSTR(toChkStr,'1,0,0') OR INSTR(toChkStr,'0,0,0');