【力扣学习笔记数据库】180.连续出现的数字

【问题描述】

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

Id Num
1 1
2 1
3 1
4 2
5 1
6 2
7 2

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

得到的结果集:

ConsecutiveNums
1

笔者一开始的程序如下:

select l1.Num AS ConsecutiveNums 
from Logs as l1
left join Logs as l2 on l1.Id+1=l2.Id
left join Logs as l3 on l2.Id +1 = l3.Id 
where l1.Num = l2.Num = l3.Num

思路如下:相当于三张表做查询,连续的意思就是 后者的Id 是前者的 Id +1 , 但同时Num保持不变。笔者以为我是对的,很遗憾我是错的。

{
     "headers": {
     "Logs": ["Id", "Num"]}, "rows": {
     "Logs": [[1, -1], [2, -1], [3, -1]]}}

对于上面的例子,笔者查出来的结果是:

{
     "headers":["ConsecutiveNums"],"values":[]}

很显然不对,所以笔者改成这个:

select l1.Num AS ConsecutiveNums 
from Logs as l1
left join Logs as l2 on l1.Num = l2.Num
left join Logs as l3 on l2.Num = l3.Num
where l1.Id = l2.Id -1  and l2.Id = l3.Id-1

这样写对于上述的测试案例来书欧式可行的,但这还有个问题,就是这个:

{
     "headers": {
     "Logs": ["Id", "Num"]}, "rows": {
     "Logs": [[1, 3], [2, 3], [3, 3], [4, 3]]}}

那么我们就需要加一个去重操作:

select distinct(l1.Num) AS ConsecutiveNums 
from Logs as l1
left join Logs as l2 on l1.Num = l2.Num
left join Logs as l3 on l2.Num = l3.Num
where l1.Id = l2.Id -1  and l2.Id = l3.Id-1

你可能感兴趣的:(SQL)