【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)
相关推荐
v***5651 小时前
PostgreSQL 中进行数据导入和导出
大数据·数据库·postgresql
q***72563 小时前
Redis-配置文件
数据库·redis·oracle
不可描述的两脚兽3 小时前
Redis 快记
java·数据库·redis
h***34633 小时前
【MySQL】表的基本操作
数据库·mysql·oracle
SelectDB4 小时前
为什么实时更新场景下 Doris 查询性能是 ClickHouse 的 34 倍
数据库
n***63274 小时前
MySQL数据库的数据文件保存在哪?MySQL数据存在哪里
数据库·mysql
SelectDB5 小时前
从 Flink 到 Doris 的实时数据写入实践——基于 Flink CDC 构建更实时高效的数据集成链路
数据库
普通网友5 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
月上柳青5 小时前
OpenWrt系统上配置batman-adv快速开始与配置详解
开发语言·mysql·php
t***26595 小时前
【大数据】MySQL与Elasticsearch的对比分析:如何选择适合的查询解决方案
大数据·mysql·elasticsearch