表:Logs+-------------+---------+| Column Name | Type |+-------------+---------+| id | int || num | varchar |+-------------+---------+id 是这个表的主键。编写一个 SQL 查询,查找所有至少连续出现三次的数字。返回的结果表中的数据可以按 任意顺序 排列。查询结果格式如下面的例子所示:示例 1:输入:Logs 表:+----+-----+| Id | Num |+----+-----+| 1 | 1 || 2 | 1 || 3 | 1 || 4 | 2 || 5 | 1 || 6 | 2 || 7 | 2 |+----+-----+输出:Result 表:+-----------------+| ConsecutiveNums |+-----------------+| 1 |+-----------------+解释:1 是唯一连续出现至少三次的数字。来源:力扣(LeetCode)链接:https://leetcode.cn/problems/consecutive-numbers
#测试数据Create table If Not Exists Logs (id int, num int);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');
#方法1selectdistinct b.num ConsecutiveNumsfrom (selecta.num,(row_number() over (order by a.id asc) -row_number() over (partition by a.num order by a.id asc)) as series_idfrom logs a) bgroup by b.num, b.series_idhaving count(1) >= 3;#方法2with tmp as (selecta.id,a.num,row_number() over(order by a.id) rnfrom Logs awhere (a.id,a.num) not in (select b.id+1,b.num from Logs b)or (a.id,a.num) not in (select c.id-1,c.num from Logs c))selecta.num ConsecutiveNumsfrom tmp ainner join tmp bon a.rn = b.rn-1and a.num = b.numand b.id - a.id >=2group by a.num;

文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




