这个想法是看看差距从哪里开始。让我假设您使用的是 SQL Server 2012,并且有lag()
和lead()
函数。以下得到下一个id
:
select t.*, lead(id) over (order by id) as nextid
from t;
如果有差距,那么nextid <> id+1
。您现在可以使用 来表征差距where
:
select id+1 as FirstMissingId, nextid - 1 as LastMissingId
from (select t.*, lead(id) over (order by id) as nextid
from t
) t
where nextid <> id+1;
编辑:
如果没有lead()
,我会对相关子查询做同样的事情:
select id+1 as FirstMissingId, nextid - 1 as LastMissingId
from (select t.*,
(select top 1 id
from t t2
where t2.id > t.id
order by t2.id
) as nextid
from t
) t
where nextid <> id+1;
假设id
是表上的主键(或者甚至它只有一个索引),这两种方法都应该具有合理的性能。