【mysql】下一行减去上一行数据、自增序列场景应用

背景

想获取if_yc为1连续账期数据
在这里插入图片描述

思路

  1. 获取所有if_yc为1的账期数据
  2. 下一行减去上一行账期,如果为1则为连续,不等于1就为断档
  3. 获取不等于1的最小账期,就是离当前账期最近连续账期

代码

以下为mysql语法:

select acct_month
from(
select (@m:=@m+1) rn,acct_month
from(
select '202311' acct_month,1 if_yc
union all 
select '202310',1
union all 
select '202309',1
union all 
select '202308',0
union all 
select '202307',1
union all 
select '202306',1) a,(select @m:=0) b
where if_yc = 1 
order by acct_month desc 
) m ,
(select min(t1.rn)+1 rn1-- ,t1.acct_month-t2.acct_month
from (
select (@i:=@i+1) rn,acct_month
from(
select '202311' acct_month,1 if_yc
union all 
select '202310',1
union all 
select '202309',1
union all 
select '202308',0
union all 
select '202307',1
union all 
select '202306',1) a,(select @i:=0) b
where if_yc = 1 
order by acct_month desc ) t1 ,
(
select (@j:=@j+1) rn,acct_month
from(
select '202311' acct_month,1 if_yc
union all 
select '202310',1
union all 
select '202309',1
union all 
select '202308',0
union all 
select '202307',1
union all 
select '202306',1) a,(select @j:=-1) b
where if_yc = 1 
order by acct_month desc 
) t2 where t1.rn = t2.rn and t1.acct_month-t2.acct_month <> 1 ) n 
where rn < n.rn1
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值