【SQL】连续出现的数字

目录

题目

分析

代码


题目

表:Logs

复制代码
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
在 SQL 中,id 是该表的主键。
id 是一个自增列。

找出所有至少连续出现三次的数字。

返回的结果表中的数据可以按 任意顺序 排列。

结果格式如下面的例子所示:

示例 1:

复制代码
输入:
Logs 表:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
输出:
Result 表:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
解释:1 是唯一连续出现至少三次的数字。

分析

找出所有至少连续出现三次的数字

单纯面向题目,三表连接或者子查询即可实现

where in 找到id连续三次的数字

即(id,num)中id+1,+2,num不变

where (id+1,num) in (select * from Logs)

and (id+2,num) in (select * from Logs)

可能检索到同一数字

通过distinct每个数字仅取一次,select distinct num as ConsecutiveNums

代码

复制代码
select distinct num as ConsecutiveNums
from Logs
where (id+1,num) in (select * from Logs)
and (id+2,num) in (select * from Logs)
相关推荐
合作小小程序员小小店40 分钟前
桌面开发,在线%幼儿教育考试管理%系统,基于eclipse,java,swing,mysql数据库
java·数据库·sql·mysql·eclipse·jdk
c***V32341 分钟前
免费的Web安全培训课程,OWASP Top 10
数据库·安全·web安全
e***74951 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
2501_941112072 小时前
深入理解Python的if __name__ == ‘__main__‘
jvm·数据库·python
2501_941112052 小时前
Python Lambda(匿名函数):简洁之道
jvm·数据库·python
合作小小程序员小小店2 小时前
web网页开发,在线短视频管理系统,基于Idea,html,css,jQuery,java,springboot,mysql。
java·前端·spring boot·mysql·vue·intellij-idea
猿小喵2 小时前
浅谈MySQL主从复制
数据库·mysql
_Minato_2 小时前
数据库知识整理——SQL访问控制
数据库
BullSmall2 小时前
高斯数据库 (GaussDB) 使用指南
数据库·gaussdb
马克学长2 小时前
SSM旅游管理系统3ohx4(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·旅游管理系统·ssm 框架