繁体   English   中英

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

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

我正尝试在此表中找到最小的遗漏号码。

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

在数字列中,您可以看到数字之间存在多个间隙。 我需要在最小间距后得到数字。 因此,在上述情况下,我需要数字3。因为2是间隔后的最小数字。

我会用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”,则返回该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;

由于使用窗口函数,许多方式在当今可能很流行。

;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

这是使用LEFT JOIN减少整体代码的一种

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

因为我只是在写更多代码,所以这里是使用EXISTS代码

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

这是一个链接,显示所有3个起作用的选项http://rextester.com/TIFRI87282

此解决方案将为您提供序列中缺少的最小数字,而不是单个数字..这将使用数字表

在这里演示

;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