【SQL刷题系列】:leetcode180 Consecutive Numbers

▌刷题回顾app


【SQL刷题系列】:leetcode178 Rank Scores
ide

【SQL刷题系列】:leetcode183 Customers Who Never Order
spa


▌题目描述3d


Write a SQL query to find all numbers that appear at least three times consecutively.code

写一段SQL查询语句,找到全部出现至少连续三次的数字。orm


+----+-----+
| 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.three

例如,给定上面的logs表,其中 “1” 是惟一一个出现至少连续三次的数字。ci


+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

▌参考答案leetcode


参考1:get

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


参考2:

Select distinct(l1.num) as consecutivenums 
from Logs l1, Logs l2, Logs l3 
where l1.num = l2.num and l2.num = l3.num and 
l2.id = l1.id+1 and l3.id = l2.id+1;


▌答案解析


参考1:建立将3个自链接表,并经过减法把3个表中3个连续id链接起来。最后使用where条件限制3个连续id对应的num值相等。


参考2:其实和参考1是一个思路,不一样的地方是自链接是彻底按照原有id来链接的,没有错位,而错位的地方在where的限制条件中:3个id的大小顺序用加法实现。

相关文章
相关标签/搜索