欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 【SQL】连续出现的数字

【SQL】连续出现的数字

2025/5/30 1:34:12 来源:https://blog.csdn.net/weixin_73404807/article/details/141464251  浏览:    关键词:【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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词