简体   繁体   English

使用 SQL Server 查找列中的间隙

[英]Finding gap in column with SQL Server

I have a table with a column, int type, it's not the primary key.我有一个带有列的表,int 类型,它不是主键。 I have thousand of record.我有数千条记录。

I'd like to find the missing ids.我想找到丢失的 ID。

I have these data :我有这些数据:

1
2
3
4
6
8
11
14

I'd like have this as result : 5,7,9,10,12,13我想要这个结果:5,7,9,10,12,13

DO you know how I can do this ?你知道我怎么做吗?

Thanks,谢谢,

It is easier to get this as ranges:将其作为范围更容易:

select (col + 1) as first_missing, (next_col - 1) as last_missing
from (select t.*, lead(col) over (order by col) as next_col
      from t
     ) t
where next_col <> col + 1;

If you actually want this as a list, I would suggest a recursive CTE:如果您确实希望将其作为列表,我建议使用递归 CTE:

with cte as (
      select t.col, lead(col) over (order by col) as next_col, 1 as lev
      from t
      union all
      select cte.col + 1, next_col, lev + 1
      from cte
      where col + 1 < next_col
     )
select cte.col
from cte
where lev > 1;

Note: If the gaps can be more than 100, you will need OPTION (MAXRECURSION 0) .注意:如果间隙可以超过 100,您将需要OPTION (MAXRECURSION 0)

Here is a db<>fiddle. 是一个 db<>fiddle。

Assuming mytab is your table, the relevant column is mycol and the potential values are 1-10,000假设mytab是您的表,相关列是mycol并且潜在值是 1-10,000

with t(i) as (select 1 union all select i+1 from t where i<10)
    ,all_values(mycol) as (select row_number() over (order by (select null)) from t t0,t t1,t t2, t t3)
select *
from   all_values a left join mytab t on a.mycol = t.mycol
where  t.mycol is null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM