leetCode之 连续出现的数字 sql语句

1.题目
有表Logs,要求编写一个 SQL 查询,查找所有至少连续出现三次的数字
在这里插入图片描述
2.我的答案
select DISTINCT Num as ConsecutiveNums
from
(
select num ,
case
when @agent = num then @count := @count + 1
when (@agent := num) is not null then @count :=1
end as cnt
from Logs , (select @agent := null , @count := null) as d
) as tmp
where tmp.cnt>=3

3.知识点
(1)子查询必须加别名,不加报错
(2)@name 是声明一个临时变量
(3)在条件判断语句中 ’ = ’ 是用来逻辑判断的,’ := ’ 是用来赋值的
(4)case用法在 https://mp.csdn.net/postedit/90413618

4.语句解析
(1)首先在Logs每条记录中加个字段记录出现的次数
select num ,
case
when @agent = num then @count := @count + 1 #连续出现时count会渐增
when (@agent := num) is not null then @count :=1 #为每一个第一次出现的count都初始化为1
end as cnt
from Logs , (select @agent := null , @count := null) as dec
效果如下
在这里插入图片描述
(2)拿出出现次数不少于3的num
select DISTINCT Num as ConsecutiveNums
from
(
select num ,
case
when @agent = num then @count := @count + 1
when (@agent := num) is not null then @count :=1
end as cnt
from Logs , (select @agent := null , @count := null) as d
) as tmp
where tmp.cnt>=3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值