【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)
相关推荐
点云SLAM3 小时前
BOOS库中Graph模块boost::edge_reverse_t和boost::vertex_color_t解读
数据库·edge·图论·bfs·dfs/拓扑排序·boost库、
尽兴-3 小时前
《深入剖析:全面理解 MySQL 的架构设计》
数据库·mysql·数据库架构设计·理解mysql架构
在风中的意志3 小时前
[数据库SQL] [leetcode] 2388. 将表中的空值更改为前一个值
数据库·sql·leetcode
梦幻通灵3 小时前
Mysql字段判空实用技巧
android·数据库·mysql
酸菜牛肉汤面5 小时前
23、varchar与char的区别
数据库
To Be Clean Coder5 小时前
【Spring源码】getBean源码实战(三)
java·mysql·spring
AI题库5 小时前
PostgreSQL 18 从新手到大师:实战指南 - 2.5 Serverless PostgreSQL
数据库·postgresql·serverless
IT技术分享社区5 小时前
数据库实战:MySQL多表更新JOIN操作的底层原理与性能调优指南
数据库·mysql·程序员
廋到被风吹走5 小时前
【数据库】【Oracle】分区表与大表设计
数据库·oracle
UrSpecial6 小时前
InnoDB存储引擎
数据库·mysql