【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)
相关推荐
index_all几秒前
虾皮(Shopee)商品ID获取商品详情请求示例
数据库·python·搜索引擎
PlumCarefree41 分钟前
SQL中的左连接,体会一对多
数据库·sql
Full Stack Developme42 分钟前
SQL 窗口函数
数据库·sql
库海无涯43 分钟前
适合DBA的brew上手指南
数据库·mysql·postgresql·mariadb
Full Stack Developme1 小时前
SQL HAVING 1 的用法解析
数据库·sql
{⌐■_■}1 小时前
【PostgreSQL】pg各版本选用取舍逻辑与docker安装postgres:15
数据库·docker·postgresql
明月看潮生1 小时前
青少年编程与数学 02-011 MySQL数据库应用 15课题、备份与还原
数据库·mysql·青少年编程·编程与数学
Elastic 中国社区官方博客1 小时前
Elasticsearch:构建 AI 驱动的搜索体验
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
赵渝强老师1 小时前
【赵渝强老师】达梦数据库的物理存储结构
数据库·oracle
the sun341 小时前
数据库的DDL操作
数据库