话不多说, 先看数据表信息.
数据表信息:
logs 表, 包含对应的编号 id, 和出现的数字Num.
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
话不多说, 再看需求~
需求:
编写一个 SQL 查询,查找所有至少连续出现三次的数字。输出如下结果:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
话不多说, 进行拆解~
拆解:
这里首先想到的是使用lead
窗口函数, 将当前结果往后移动一个, 往后移动二个, 当三者结果一致, 则说明该数字出现过三次.
直接上SQL语句:
sql
select
id, num,
lead(num, 1) over(order by id) as num_1,
lead(num, 2) over(order by id) as num_2
from logs
;
结果如下:
再加上限制条件:
sql
select t.id
from (
select
id, num,
lead(num, 1) over(order by id) as num_1,
lead(num, 2) over(order by id) as num_2
from logs
) as t
where t.num = t.num_1
and t.num = t.num_2
;
就可以得到最终的结果:
最后给大家介绍一下我这边的操作步骤, 想要自己测试的话, 可以参考:
sql
CREATE TABLE logs (
Id INT,
Num INT
);
INSERT INTO logs (Id, Num)
VALUES (1, 1), (2, 1), (3, 1), (4, 2), (5, 1), (6, 2), (7, 2);