SQL 序列缺失数字汇总

SQL summary of missing numbers in sequence

我想找出序列中的空缺,并按以下方式总结结果:

数列: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,table 称为 BSEG

编辑: 在 Gaps and Islands material 的帮助下,我找到了解决方案(可能不是最佳解决方案,但我认为它有效):

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 

这就是孤岛和缺口问题。在这里阅读更多内容:

https://www.simple-talk.com/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/

The word ‘Gaps’ in the title refers to gaps in sequences of values. Islands are unbroken sequences delimited by gaps. The ‘Gaps and Islands’ problem is that of using SQL to rapidly detect the unbroken sequences, and the extent of the gaps between them in a column.