【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)
相关推荐
花月C几秒前
基于Redis的BitMap数据结构实现签到业务
数据结构·数据库·redis
hgz07102 分钟前
数据库事务
数据库·mysql
老华带你飞8 分钟前
二手商城|基于springboot 二手商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
@小码农10 分钟前
6547网:2025年9月 Python等级考试(三级)真题及答案
服务器·数据库·python
千寻技术帮11 分钟前
10393_基于SSM的杂志订阅网站管理系统
mysql·毕业设计·ssm·安装·文档·杂志订阅
IT教程资源C14 分钟前
(N_122)基于springboot,vue网上订餐系统
mysql·vue·前后端分离·网上订餐系统·springboot网上订餐
老华带你飞24 分钟前
酒店预约|基于springboot 酒店预约系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
晨曦54321025 分钟前
MySQL MOD()函数详解与Python对比
sql
spencer_tseng36 分钟前
mysql-8.0.44-winx64.msi VC_redist.2019.x64.exe
mysql
何妨呀~37 分钟前
mysql 8服务器实验
android·mysql·adb