180.(Medium)连续出现的数字
表:Logs
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| num | varchar |
+-------------+---------+
id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
查询结果格式如下面的例子所示:
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.com/problems/consecutive-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
select 里的每个字段的相关计算是按顺序执行的
case when 的条件判断句是按顺序执行的,既能判断又能赋值。。。
SELECT DISTINCT Num ConsecutiveNums
FROM
(
SELECT Num,
case
WHEN @prev = Num then @cnt:=@cnt+1 -- when clause 1
WHEN (@prev:= Num) is not null then @cnt:=1 -- when clause 2
end cnt
FROM Logs, (SELECT @prev:=null, @cnt:=null) t1
) t2
WHERE cnt >=3;
when clause 1 在第一行必跳过
when 2 条件总是true,执不执行完全取决于when 1 是否为true:第一条false了,就执行 @cnt:=1;第一条 true了,压根到不了这一条。
Table Schema
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');
Last updated
Was this helpful?