【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)
相关推荐
砚边数影2 小时前
运营商网管系统重构:如何解决海量投诉数据下的“查询延迟”与“写入瓶颈”?
网络·数据库·时序数据库·kingbase·kingbasees·数据库平替用金仓·金仓数据库
shsh2002 小时前
mybatis plus打印sql日志
数据库·sql·mybatis
山峰哥3 小时前
数据库调优实战:索引策略与查询优化案例解析
服务器·数据库·sql·性能优化·编辑器
c***03233 小时前
MySQL 启动失败 (code=exited, status=1FAILURE) 异常解决方案
数据库·mysql
ritxgt0063 小时前
MySQL 数据增删改查
android·数据库·mysql
t***44234 小时前
mysql之数字函数
数据库·mysql
zlpzpl4 小时前
MySQL 的 INSERT(插入数据)详解
android·数据库·mysql
爱考证的小刘4 小时前
Oracle OCP、MySQL OCP数据库证书怎么选?
mysql·oracle·oracle数据库·oracle认证·mysql自学·mysql题库·oracle学习
摩拜芯城IC4 小时前
8通道TDM分组传输IC DS34S108GN芯片参数资料 E1/T1分组化芯片
数据库
u***35745 小时前
MySQL ——数据的增删改查
数据库·mysql