[英]Find missing numbers in a sequence in MS SQL
Say i have a table with an integer column Id.假设我有一个带有整数列 Id 的表。 I need to find the
missing numbers
in a sequence
with a maximum returned amount.我需要在具有最大返回金额的
sequence
找到missing numbers
。
How can i achive this in one single query using MS SQL
?如何使用
MS SQL
在单个查询中实现这一目标?
Thanks in advance!提前致谢!
Try this:试试这个:
If you need to get more numbers, just increase the WHERE Number<=100
.如果您需要获得更多数字,只需增加
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);
Existing values:现有值:
Number
1
3
5
7
9
OutPut:输出:
Number
2
4
6
8
10
Hope this helps you.希望这对你有帮助。
This should work这应该工作
There are also a system table with numbers还有一个带数字的系统表
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.