LeetCode--SQL 查询:查找所有至少连续出现三次的数字。

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/consecutive-numbers

select distinct Num as ConsecutiveNums
from (
  select Num, 
  case 
    when @prev = Num then @count := @count + 1
    when (@prev := Num) is not null then @count := 1
  end as CNT
  from Logs, (select @prev := null,@count := null) as t
) as temp
where temp.CNT >= 3

# SQL查询先看from,上边form表,还有初始化了pre、count为null,分别记录上一个数字已经连续出现的次数。
# 然后调用if()函数,如果pre和当前行数字相同,count加1极为连续出现的次数;
# 如果不同,意味着重新开始一个数字,count重新从1开始。
# 注意:pre初始值最好不要赋值为一个数字,因为不确定赋值的数字是否会出现在测试表中。

猜你喜欢

转载自www.cnblogs.com/jongty/p/12620090.html