题目:https://leetcode-cn.com/problems/consecutive-numbers/
表:Logs
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| num | varchar |
+-------------+---------+
id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
查询结果格式如下面的例子所示:
Logs 表:
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
Result 表:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
1 是唯一连续出现至少三次的数字。
代码:
select distinct t.Num as ConsecutiveNums from (select Num, lead(Num, 1, null) over(order by Id) as r1, lead(Num, 2, null) over(order by Id) as r2 from Logs) t where t.r1 - t.Num = 0 and t.r2 - t.r1 = 0
注意lead里面default不能是0,需写为null,因为可能存在最后几行Num=0的情况
注意连续类的题不能用group by