oracle中sql当前序列号,Oracle中获取连续的序列号范围的SQL (二)

所谓连续的序列号就是看相同格式的情况下前一行记录与当前行的记录序号的值是否相差为1:

如果相差为1,则说明两个序列号是连续的;

如果不为1,则两个序列号不是连续的

select numFormat,

lag(code, 1) over(partition by numFormat order by code) previousCode, code,

max(code) over(partition by numFormat) maxn

from inventory;

49cf3a00038eab7cd64530e77094e6df.png

2:过滤掉中间连续序列号。

这里通过比较当前序列号与前一行的序列号相减是非相差为1,相差为1将被过滤掉;相差不为1比如2或者说有null值则不被过滤。

select * from(

select numFormat,

lag(code, 1) over(partition by numFormat order by code) previousCode, code,

max(code) over(partition by numFormat) maxn

from inventory

)

where nvl(code-previousCode-1,1) <> 0

;

48ebaeeec99f304fdbad24e0e85087d4.png

3:把当前行的code列作为 startNum,后一行的previouscode列作为endNum

select numFormat,code startNum, lead(previousCode) over(partition BY numFormat order by previousCode ) endNum from(

select numFormat,

lag(code, 1) over(partition by numFormat order by code) previousCode, code,

max(code) over(partition by numFormat) maxn

from inventory

)

where nvl(code-previousCode-1,1) <> 0

;

5f221341be4e653f86b64e64194e6e43.png

但是我们这里却得到了错误的结果。

这里面有两个问题:

使用lead函数往后找的过程中,如果当前行已经是最后一行,则应该使用最大数字作为endNum,所以需要使用nvl函数来判断是否为null。

本该是第一行的的记录跑startNum为1的居然放到了最后一行。经过调查,previousCode的值存在为null的情况,oracle通常遇到为null值是把null放在最后,所以我们需要添加previousCode为null的行要排在前面。使用nulls first.

4:修复第3步的问题。

select numFormat,code startNum, nvl(lead(previousCode) over(partition BY numFormat order by previousCode nulls first ),maxn) endNum from(

select numFormat,

lag(code, 1) over(partition by numFormat order by code) previousCode, code,

max(code) over(partition by numFormat) maxn

from inventory

)

where nvl(code-previousCode-1,1) <> 0

;

注意红色部分的修改,这样就可以得到如下正确的结果。

67f7a0c57ce2233b1ea2b27ff9debd04.png

Oracle中获取连续的序列号范围的SQL (二)

标签:前一行   存在   tor   mat   添加   记录   orm   Inventor   for

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉 本文系统来源:https://www.cnblogs.com/pmh905001/p/12244514.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值