180. 连续出现的数字
题目描述
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
Id | Num |
---|---|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 2 |
5 | 1 |
6 | 2 |
7 | 2 |
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。
ConsecutiveNums |
---|
1 |
实现
方法1(三表连接查询)
思路:Logs表中是否有3行,Id的关系是id2=id1+1,id3=id2+1;并且Num相同。
select distinct a.Num ConsecutiveNums
from Logs a, Logs b, Logs c
where a.Num = b.Num and b.Num = c.Num and b.Id = (a.Id + 1) and c.Id = (b.Id + 1);
方法2(in)
思路:对于Logs表的每一行,是否存在下面的2行(id+1和id+2),Num相同
select distinct Num ConsecutiveNums
from Logs
where (id + 1, Num) in (select * from Logs)
and (id + 2, Num) in (select * from Logs);