且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SQL Server 中查找数字序列中的间隙

更新时间:2022-04-13 09:14:18

我会使用 lead():

select min(id) + 1
from (select t.*,
             lead(id) over (order by id) as next_id
      from t
     ) t
where next_id <> id + 1;

如果您想确保 id 从 1 开始(因此如果缺少1",则返回),您可以这样做:

If you want to ensure that the ids start at 1 (so if "1" is missing, then return that), you can do:

select (case when min(minid) <> 1 then 1 else min(id) + 1 end)
from (select t.*, min(id) over () as minid
             lead(id) over (order by id) as next_id
      from t
     ) t
where next_id <> id + 1;