▌刷题回顾
【SQL刷题系列】:leetcode178 Rank Scores
【SQL刷题系列】:leetcode183 Customers Who Never Order
▌题目描述
Write a SQL query to find all numbers that appear at least three times consecutively.
写一段SQL查询语句,找到所有出现至少连续三次的数字。
+----+-----+ | 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.
例如,给定上面的logs表,其中 “1” 是唯一一个出现至少连续三次的数字。
+-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+
▌参考答案
参考1:
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的大小顺序用加法实现。