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;
相关推荐
掉头发的王富贵几秒前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
小云数据库服务专线12 分钟前
GaussDB数据库架构师修炼(十六) 如何选择磁盘
数据库·数据库架构·gaussdb
叽哥39 分钟前
Kotlin学习第 1 课:Kotlin 入门准备:搭建学习环境与认知基础
android·java·kotlin
风往哪边走1 小时前
创建自定义语音录制View
android·前端
用户2018792831671 小时前
事件分发之“官僚主义”?或“绕圈”的艺术
android
用户2018792831671 小时前
Android事件分发为何喜欢“兜圈子”?不做个“敞亮人”!
android
码出财富1 小时前
SQL语法大全指南
数据库·mysql·oracle
Kapaseker3 小时前
你一定会喜欢的 Compose 形变动画
android
异世界贤狼转生码农3 小时前
MongoDB Windows 系统实战手册:从配置到数据处理入门
数据库·mongodb
QuZhengRong3 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel