zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Leetcode No.180 连续出现的数字

2023-03-20 14:56:43 时间

一、题目描述

表: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 是唯一连续出现至少三次的数字。

二、思路

使用lag窗口函数

三、代码

select distinct(Num) ConsecutiveNums
from(
    select Num,
    lag(Num,1)over(order by id desc) as last1,
    lag(Num,2)over(order by id desc) as last2
    from Logs
)a
where Num=last1 and Num=last2