t-sql找到最小值

时间:2011-12-29 08:02:19

标签: sql-server tsql

如何找到未填充或不存在的值中的最小值

例如

001  
002  
003
013
015

结果必须返回004

选择分钟

5 个答案:

答案 0 :(得分:3)

declare @T table(Number int)

insert into @T values (1),(2),(3),(13),(15)

select top 1 Number + 1
from @T
where Number + 1 not in (select Number from @T)
order by Number

<强>更新

使用char(3)零填充的版本。

declare @T table(ID char(3))

insert into @T values ('001'),('002'),('003'),('013'),('015')

select top 1 right(1001 + Id, 3)
from @T
where Id + 1 not in (select Id from @T)
order by Id

答案 1 :(得分:1)

假设您的序列在表YourNumbersTable中 试试这个(SQL Server 2005 +):

declare @min int, @max int
select @min = MIN(Id), @max = MAX(Id) from YourNumbersTable

;WITH numbers(id) as
(
    SELECT @min id
    UNION ALL 
    SELECT id+1
    FROM numbers
    WHERE id <= @max
)

SELECT MIN(Numbers.id)
FROM Numbers
     LEFT JOIN YourNumbersTable ON Numbers.Id = YourNumbersTable.Id
WHERE YourNumbersTable.Id IS NULL
OPTION(MAXRECURSION 0)

答案 2 :(得分:1)

试试这个(没有连接,没有记录)

declare @T table(n int)

insert into @T values (1),(2),(3),(13),(15)


select max(n)+1 from (
  select *,l=n-row_number() over(order by n)  
    from (
      select n from @T
      union
      select 0 -- what about 0 ??
    ) as s
) as a
where l=-1

答案 3 :(得分:1)

这类似于what @szauri has suggested,但没有汇总:

;
WITH ranked AS (
  SELECT n, r = ROW_NUMBER() OVER (ORDER BY n)
  FROM @T
)
SELECT TOP 1 r
FROM ranked
WHERE n <> r
ORDER BY n

注意:@ szauri和我的解决方案都需要SQL Server 2005或更高版本。

答案 4 :(得分:0)

也许我有另一种解决方案。由于其中的循环,它在宽数范围内可能会更慢。

-- prepare a table to have your example 
declare @ref table (id int)
insert into @ref (id) values (1), (2), (3), (13), (15)

-- this will return 1
select min(id) from @ref

-- magic happens here
declare @i int, @max int, @returnValue int
select @i = min(id), @max = max(id) from @ref
declare @tmp table (id int)
while @i <= @max
    begin
    insert into @tmp (id) values (@i)
    set @i = @i + 1
    end

select @returnValue = min(t.id) 
    from @tmp t left outer join @ref r on t.id = r.id
    where r.id is null

-- this will return 4
select @returnValue