如何找到最小的缺失序列号

时间:2019-03-18 05:32:31

标签: sql sql-server

我有一张桌子,上面有序列号。

我想找到丢失的序列号,这是丢失的序列号中的最小值。

For eg.,

Seq No: 1,2,3,5,7,9 ==> Expected result: 4
Seq No: 1,2,3,4,5,6,7,9,15 ==> Expected result: 8

3 个答案:

答案 0 :(得分:2)

您可以尝试使用row_number()

with cte as
(
select seq,seq-row_number() over(order by seq) as diff
from tablename
)
select * from cte where diff<>0 and diff in (select min(diff) from cte where diff<>0)

答案 1 :(得分:2)

使用row_number()生成一个新序列,并将其与原始序列进行比较

select  min(new_seq)
from
(
    select  *, new_seq = row_number() over (order by seq)
    from    your_table
) t
where   seq <> new_seq

答案 2 :(得分:2)

选择不包含序列号加一的最小序列号,然后添加一个:

select min(seqNo)+1 from SeqNoTable where seqNo+1 not in (select SeqNo from SeqNoTable)