我想找出一个序列中的空白,并通过以下方式总结这些发现:
数字序列:2, 3, 4, 8, 9, 12, 13, 14, 15
缺少数字:0, 1, 5, 6, 7, 10, 11
最小数字:0(始终)
最大数字:序列的最大数字(本例中为 15)
摘要应如下所示:
From | To | # of missing
00 | 01 | 2
05 | 07 | 3
10 | 11 | 2
我正在使用 SQL 服务器,实际上,该序列将包含更多数字(接近一百万)。我发现许多脚本可以找到并列出序列中缺失的数字,但我不知道如何以所需的方式对其进行总结。
如果有帮助,则调用该字段并调用BELNR
该表BSEG
。
编辑:在间隙和岛屿材料的帮助下,我已经找到了一个解决方案(可能不是最佳解决方案,但我认为它有效):
with C as
(
select belnr, row_number() over(order by belnr) as rownum
from bseg
)
select cast(Cur.belnr as bigint) + 1 as [From], cast(nxt.belnr as bigint) - 1 as [To], (cast(nxt.belnr as bigint) - 1) - (cast(Cur.belnr as bigint) + 1) + 1 as [# of Missing]
from C as Cur
join C as Nxt
on Nxt.rownum = cast(Cur.rownum as int) +1
Where cast(nxt.belnr as bigint) - cast(Cur.belnr as bigint) > 1