简体   繁体   English

如何在SQL Server中的数字序列中查找空格

[英]How to find gaps in a sequence of numbers in SQL Server

I am trying to find the smallest missing number in this table. 我正尝试在此表中找到最小的遗漏号码。

+------+--------+
| id   | number |
+------+--------+
|  902 |    1   |
|  908 |    2   |
| 1007 |    7   |
| 1189 |    8   |
| 1233 |   12   |
| 1757 |   15   |
+------+--------+

In the number column, you can see there are several gaps between the numbers. 在数字列中,您可以看到数字之间存在多个间隙。 I need to get the number after the smallest gap. 我需要在最小间距后得到数字。 So in the case above I need the number 3. Because 2 is the smallest number after a gap. 因此,在上述情况下,我需要数字3。因为2是间隔后的最小数字。

I would use lead() : 我会用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;

If you want to ensure that the ids start at 1 (so if "1" is missing, then return that), you can do: 如果要确保ID从1开始(因此,如果缺少“ 1”,则返回该ID),可以执行以下操作:

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;

Lots of different ways here is one that is probably popular these days due to using window functions. 由于使用窗口函数,许多方式在当今可能很流行。

;WITH cte AS (
    SELECT
       Id
       ,[Number]
       ,LAG([Number],1,NULL) OVER (ORDER BY [Number] ASC) AS LagValue
    FROM
       @Table
)

SELECT
    MIN(LagValue) + 1 AS SmallestNumberAfterGap
FROM
    cte
WHERE
    LagValue <> [Number] - 1

And here is one that is less overall code using an LEFT JOIN 这是使用LEFT JOIN减少整体代码的一种

SELECT
    MIN(t2.[Number]) + 1 AS SmallestNumberAfterGap
FROM
    @Table t1
    LEFT JOIN @Table t2
    ON t1.Number + 1 = t2.Number

And because I am just writing more code here is one using EXISTS 因为我只是在写更多代码,所以这里是使用EXISTS代码

SELECT
    MIN(t1.Number) + 1 AS SmallestNumberAfterGap
FROM
    @Table t1
WHERE
    NOT EXISTS (SELECT * FROM @Table t2 WHERE t1.Number + 1 = t2.Number)

Here is a link showing all 3 options functioning http://rextester.com/TIFRI87282 这是一个链接,显示所有3个起作用的选项http://rextester.com/TIFRI87282

This solution will give you the minimum numbers missing from sequence not a single number .. This uses a numbers table .. 此解决方案将为您提供序列中缺少的最小数字,而不是单个数字..这将使用数字表

Demo Here 在这里演示

;With cte
as
(
select 
*
from 
Numbers n
left join
#t1
on n.Number=#t1.num
where n.Number<=(select max(num) from #t1)

)
select 
number from cte c1
join
#t1
on #t1.num+1=c1.Number
where c1.num is null

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

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