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;
相关推荐
消失的旧时光-19437 分钟前
摇杆控制View
android·kotlin
间彧8 分钟前
MySQL优化指南:慢查询分析工具 pt-query-digest
数据库
正在走向自律10 分钟前
从SQL Server到KingbaseES:一步到位的跨平台迁移与性能优化指南
数据库·oracle·sql server·国产数据库·kingbasees·信创改造
绵绵细雨中的乡音18 分钟前
MySQL 复合查询全解析:从单表到多表的实战进阶
mysql
游戏开发爱好者823 分钟前
iOS 抓包工具实战 开发者的工具矩阵与真机排查流程
android·ios·小程序·https·uni-app·iphone·webview
啊吧怪不啊吧23 分钟前
SQL之表的查改(上)
服务器·数据库·sql
大G的笔记本24 分钟前
Redis的内存淘汰策略
数据库·redis·缓存
爬山算法25 分钟前
Redis(90)如何配置Redis的身份验证?
数据库·redis·缓存
Sammyyyyy38 分钟前
MySQL 与 PostgreSQL,该怎么选
数据库·mysql·postgresql·开发工具·servbay
好记忆不如烂笔头abc40 分钟前
oracle rac多私网的问题
数据库·oracle