连续出现的数字

连续出现的数字_第1张图片
连续出现的数字.png

题目中求连续出现三次的数字,不容易想到的如果用sql语句限制连续,因为sql语句不是普通的编程语言,它面向集合。

自己根据题目的案例毫不犹豫的写出了下面的语句,果不其然提示出错。

 SELECT t1.Num ConsecutiveNums FROM Logs t1 LEFT JOIN Logs t2 ON t1.Id <= t2.Id and t1.Num = t2.Num  GROUP BY t1.id
 HAVING (MIN(t2.Id) - t1.id) >=2

仔细想想想了想,显然是错的,因为没有突出连续3次。后来先考虑连续两次怎么写,很简单。中间用的inner join,能够出现在结果集里面的一定是符合连续两次条件的。

SELECT DISTINCT t1.Num ConsecutiveNums FROM Logs t1 
JOIN Logs t2 ON t1.id +1 = t2.id AND t1.Num = t2.Num 

再次基础上扩充了下,得到下面的答案:

SELECT DISTINCT t1.Num ConsecutiveNums FROM Logs t1 
JOIN Logs t2 ON t1.id +1 = t2.id AND t1.Num = t2.Num 
JOIN Logs t3 ON t3.id = t2.id+1 AND t3.Num = t2.Num
GROUP BY t1.id 

你可能感兴趣的:(连续出现的数字)