▌刷题回顾


【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的大小顺序用加法实现。


©著作权归作者所有:来自51CTO博客作者mb5fe18e9fef50b的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. Python 中的数字到底是什么?
  2. 不使用 if-elif 语句,如何优雅地判断某个数字所属的等级?
  3. 起个简单枯燥的标题:找出连续差相同的数字
  4. 一道简单的数组遍历题,加上四个条件后感觉无从下手
  5. 图解「剑指Offer」之旋转数组的最小数字
  6. 动画:面试必刷之找出数组中重复的数字
  7. 基于业务和平台理解数字营销概念
  8. C语言的一些练习以及自己写一个猜数字小游戏
  9. C语言的一些练习以及写一个猜数字游戏

随机推荐

  1. c语言怎么判断奇偶数
  2. c语言的基本单位是什么?
  3. c语言怎么将小写转换为大写
  4. c语言函数返回值类型由什么决定?
  5. c语言二进制怎么转换十进制
  6. c语言中不等于怎么表示?
  7. c语言中long是什么意思?
  8. c语言中=和==的区别是什么?
  9. c语言关键字是什么
  10. c语言源程序文件的后缀是什么?