【SQL刷题系列】:leetcode180 Consecutive Numbers
16lz
2021-01-22
▌刷题回顾
【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的大小顺序用加法实现。
更多相关文章
- Python 中的数字到底是什么?
- 不使用 if-elif 语句,如何优雅地判断某个数字所属的等级?
- 起个简单枯燥的标题:找出连续差相同的数字
- 一道简单的数组遍历题,加上四个条件后感觉无从下手
- 图解「剑指Offer」之旋转数组的最小数字
- 动画:面试必刷之找出数组中重复的数字
- 基于业务和平台理解数字营销概念
- C语言的一些练习以及自己写一个猜数字小游戏
- C语言的一些练习以及写一个猜数字游戏