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;
相关推荐
IvorySQL2 小时前
PostgreSQL 技术日报 (3月7日)|生态更新与内核性能讨论
数据库·postgresql·开源
赵渝强老师3 小时前
【赵渝强老师】金仓数据库的数据文件
数据库·国产数据库·kingbase·金仓数据库
随逸1776 小时前
《Milvus向量数据库从入门到实战,手把手搭建语义检索系统》
数据库
神秘的猪头7 小时前
🚀 React 开发者进阶:RAG 核心——手把手带你玩转 Milvus 向量数据库
数据库·后端·llm
alexhilton17 小时前
端侧RAG实战指南
android·kotlin·android jetpack
0xDevNull1 天前
MySQL索引进阶用法
后端·mysql
0xDevNull1 天前
MySQL索引用法
mysql
IvorySQL1 天前
PostgreSQL 技术日报 (3月6日)|为什么 Ctrl-C 在 psql 里让人不安?
数据库·postgresql·开源
二流小码农1 天前
鸿蒙开发:路由组件升级,支持页面一键创建
android·ios·harmonyos
NineData1 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库