假设我有一个包含整数列Id的表。我需要找到1
中missing numbers
的最大退货金额。
如何使用sequence
在单个查询中实现此目的?
提前致谢!
答案 0 :(得分:3)
试试这个:
如果您需要获得更多数字,只需增加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
希望这会对你有所帮助。
答案 1 :(得分:1)
这应该有效 还有一个带数字的系统表
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 );