列表中缺少的数字或最大数量

时间:2015-03-04 10:37:57

标签: sql sql-server tsql

我正在寻找列表中缺少的数字,它工作得非常好,但是当它从2开始时,是否可以在下面插入1. 它应该提供1而不是4.请帮助谢谢

drop table #temp
create table #temp
(
Number INT
)

insert into #temp
(Number)
select 2 union all
select 3 union all
select 5


SELECT MIN(t1.Number) + 1 AS MissingNumber 
FROM #temp t1 
LEFT OUTER JOIN #temp t2 ON (t1.Number + 1 = t2.Number) 
WHERE t2.Number IS NULL

3 个答案:

答案 0 :(得分:2)

我建议您创建一个单独的numbers表来执行此操作。

有很多方法可以创建数字表。查看此link了解详情

SELECT TOP (1000) n = Row_number()OVER (ORDER BY number)
INTO   #numbers
FROM   [master]..spt_values
ORDER  BY n;

CREATE TABLE #temp
  (Number INT)

INSERT INTO #temp(Number)
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 5

SELECT Min(t1.n) AS MissingNumber
FROM   #numbers t1
       LEFT OUTER JOIN #temp t2
                    ON ( t1.n = t2.Number )
WHERE  t2.Number IS NULL 

答案 1 :(得分:0)

我认为这是不可能的,因为加入并不知道该数字从1开始。它将搜索最小值。

我们可以使用while循环来解决问题

答案 2 :(得分:0)

使用此

IF OBJECT_ID('Tempdb..#temp') IS NOT NULL 
    DROP TABLE #temp
CREATE TABLE #temp ( Number INT )
INSERT  INTO #temp
        ( Number )
VALUES  ( 2 ),
        ( 3 ),
        ( 5 );
WITH    cte
          AS ( SELECT   n = 1
               UNION ALL
               SELECT   n + 1
               FROM     cte
               WHERE    n <= 100 --can be increased with OPTION  ( MAXRECURSION {iteration value} ) at the end of the query
             )
    SELECT  MIN(cte.n) AS MissingNumber
    FROM    cte
            LEFT JOIN #temp t ON ( cte.n = t.Number )
    WHERE   t.Number IS NULL