MySQL基础练习题48-连续出现的数字

目录

题目

准备数据

分析数据


题目

找出所有至少连续出现三次的数字。

准备数据

sql 复制代码
## 创建库
create database db;
use db;

## 创建表
Create table If Not Exists Logs (id int, num int)

## 向表中插入数据
Truncate table Logs
insert into Logs (id, num) values ('1', '1')
insert into Logs (id, num) values ('2', '1')
insert into Logs (id, num) values ('3', '1')
insert into Logs (id, num) values ('4', '2')
insert into Logs (id, num) values ('5', '1')
insert into Logs (id, num) values ('6', '2')
insert into Logs (id, num) values ('7', '2')

分析数据

复制代码
1 是唯一连续出现至少三次的数字。

遇见连续性问题,需要两列差值相同的,最后进行相减,相同的即为连续。

第一步:根据num分组,id排序进行排名

sql 复制代码
select *,
       row_number() over (partition by num order by id) rn
from logs;

第二步:算差值,将id列减去rn列的值

sql 复制代码
with t1 as (
    select *,
           row_number() over (partition by num order by id) rn
    from logs
) select *,
         (id - cast(rn as signed)) as diff
from t1;

注意:rn列需要强制性转化

sql 复制代码
with t2 as (
    with t1 as (
        select *,
               row_number() over (partition by num order by id) rn
        from logs
    ) select *,
             (id - cast(rn as signed)) as diff
    from t1
) select
    distinct t2.num as ConsecutiveNums
from t2
group by t2.num,t2.diff
having count(t2.diff) >= 3;
相关推荐
晴天¥16 小时前
达梦数据库的内存结构
服务器·数据库·达梦数据库
倔强的石头_16 小时前
生产环境排坑实录:SQL 标量子查询的“静默杀手”与优化器的智能推演
数据库
Navicat中国17 小时前
使用 SSL/TLS 安全连接数据库
数据库·安全·ssl
heimeiyingwang17 小时前
【架构实战】MySQL主从复制与读写分离:数据库高可用架构
数据库·mysql·架构
Cosolar17 小时前
2026年全球向量数据库技术全景与架构演进深度解析报告
数据库·人工智能·架构·agent·智能体
IronMurphy17 小时前
Redis拷打第七讲(最终章)
数据库·redis·php
plainGeekDev17 小时前
Android性能优化面试题:你说你会优化,结果连ANR都排查不了
android·面试
张~颜17 小时前
PostgreSQL复制槽
数据库·postgresql
爱晒太阳的小老鼠17 小时前
数据库连接池Connection is not available, request timed out after 120000ms
数据库