【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)
相关推荐
冰茶_3 分钟前
掌握LINQ:查询语法与方法语法全解析
sql·学习·microsoft·微软·c#·linq
CryptoRzz9 分钟前
股票数据源对接技术指南:印度尼西亚、印度、韩国
数据库·python·金融·数据分析·区块链
Pluto_CSND18 分钟前
hbase shell的常用命令
大数据·数据库·hbase
哈哈真棒35 分钟前
sparkSQL读入csv文件写入mysql(2)
数据库·mysql
Cynicism_Smile42 分钟前
Mysql 8.0.32 union all 创建视图后中文模糊查询失效
数据库·mysql
小oo呆42 分钟前
【自然语言处理与大模型】向量数据库技术
数据库·人工智能·自然语言处理
Aurora_NeAr1 小时前
Redis设计与实现——Redis命令参考与高级特性
数据库·redis·缓存
程序猿小谢1 小时前
Redis特性与应用
数据库·redis·缓存
2401_836836591 小时前
mysql集群
mysql·adb
ZHOU_WUYI2 小时前
MySQL 与 FastAPI 交互教程
mysql·fastapi