【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)
相关推荐
SelectDB21 分钟前
5 倍性能提升,Apache Doris TopN 全局优化详解|Deep Dive
数据库·apache
JIngJaneIL1 小时前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
陈平安安1 小时前
设计一个秒杀功能
java·数据库·sql
isNotNullX2 小时前
数据处理的流程是什么?如何进行数据预处理?
数据库·数据资产管理·数据处理·企业数字化
TAEHENGV2 小时前
基本设置模块 Cordova 与 OpenHarmony 混合开发实战
android·java·数据库
Leo1872 小时前
MySQL 回表(Back to Table)详解
数据库·mysql
遇见火星2 小时前
MySQL 8.0复制架构主从自动切换脚本
mysql·adb·架构·mysql8.0·mysql主从
不知江月待何人..2 小时前
MySQL服务无法启动问题
数据库·mysql
廋到被风吹走2 小时前
【数据库】【Oracle】SQL基础
数据库·sql·oracle
曹牧2 小时前
Oracle统计每日发生次数
数据库·oracle