簡體   English   中英

在 MS SQL 中查找序列中缺失的數字

[英]Find missing numbers in a sequence in MS SQL

假設我有一個帶有整數列 Id 的表。 我需要在具有最大返回金額的sequence找到missing numbers

  • 如果表是空的並且我要 10,它應該返回數字 1-10。
  • 如果表有 1-5 並且我要 10,它應該返回數字 6、7、8、9、10、11、12、13、14、15。
  • 如果表有 1,2,4,6,9 並且我要求 10,它應該返回數字 3,5,7,8,10,11,12,13,14,15

如何使用MS SQL在單個查詢中實現這一目標?

提前致謝!

試試這個:

如果您需要獲得更多數字,只需增加WHERE Number<=100

DECLARE @Tab1 TABLE (ID INT)

INSERT INTO @Tab1 VALUES(1)
INSERT INTO @Tab1 VALUES(3)
INSERT INTO @Tab1 VALUES(5)
INSERT INTO @Tab1 VALUES(7)
INSERT INTO @Tab1 VALUES(9)

;WITH CTE AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number + 1 FROM CTE
    WHERE Number<=100
)
SELECT TOP 5 *
FROM CTE
WHERE Number NOT IN(SELECT ID FROM @Tab1)
ORDER BY Number
OPTION (maxrecursion 0);

現有值:

Number
1
3
5
7
9

輸出:

Number
2
4
6
8
10

希望這對你有幫助。

這應該工作
還有一個帶數字的系統表

declare @T table (i int primary key);
insert into @T values (1), (2), (4), (6), (9); 
declare @count int = 10;
declare @size int = (select count(*) from @T);
with cte as
( select 1 as num
  union all 
  select num + 1 
  from cte
  where num + 1 <= (@count + @size)
)
select top (@count) cte.num 
from cte 
left join @T t 
  on t.i = cte.num 
where t.i is null 
order by cte.num 
option ( MaxRecursion 0 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM