查找SQL中的所有整数间隔

Nic*_*ost 4 sql sql-server sql-server-2008

我有一个数据库,用于存储我从外部来源引入的游戏的不同比赛信息。由于一些问题,数据库中偶尔会出现空白(可能从1个丢失的ID到几百个)。我想让程序为丢失的游戏提取数据,但是我需要首先获取该列表。

这是表格的格式:

id (pk-identity)  |  GameID (int)  |  etc.  |  etc.  
Run Code Online (Sandbox Code Playgroud)

我曾想过编写一个程序来循环运行并查询从1开始的每个GameID,但似乎应该有一种更有效的方法来获取丢失的数字。

是否有使用SQL Server的简单有效的方法来查找范围中所有丢失的数字?

Gor*_*off 5

想法是看差距从哪里开始。让我假设您正在使用SQL Server 2012,因此具有lag()lead()函数。以下是下一个id

select t.*, lead(id) over (order by id) as nextid
from t;
Run Code Online (Sandbox Code Playgroud)

如果有间隙,则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;
Run Code Online (Sandbox Code Playgroud)

编辑:

没有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;
Run Code Online (Sandbox Code Playgroud)

假设s id是表上的主键(甚至只是它有一个索引),则这两种方法都应具有合理的性能。