如何获得下一个可用的最大数量?

时间:2015-04-14 22:40:31

标签: sql sql-server sql-server-2005

我的头衔有意义吗?如果没有,我很抱歉。

在此专栏中,如何进行查询,以便我可以获得5

Number
-----
  1
  2
  3
  4
  6
  7

4 个答案:

答案 0 :(得分:1)

为您的规范编辑http://www.sqlservercentral.com/Forums/Topic911849-392-1.aspx - 要查看所有缺失的数字,请删除min函数:

;WITH Tally(N) AS
(
  SELECT number N FROM master.dbo.spt_values WHERE Type = 'P' AND number > 0
)
SELECT
  min(T.N )
FROM
  Tally T
LEFT JOIN
  numbers MN ON MN.N = T.N
WHERE
  MN.N IS NULL
  AND T.N <= (SELECT MAX(N) FROM numbers)

答案 1 :(得分:0)

你想要一个更窄的版本:SQL: find missing IDs in a table

加: In SQL, how do you get the top N rows ordered by a certain column?

所以你要将LIMIT 0,1添加到MySQL中的查询

或者您将TOP 1添加到SELECT for MS SQL

在MySQL中:

declare @id int
declare @maxid int

set @id = 1
select @maxid = max(id) from tbl

create temporary table IDSeq
(
    id int
)

while @id < @maxid
begin
    insert into IDSeq values(@id)

    set @id = @id + 1
end

select 
    s.id 
from 
    idseq s 
    left join tbl t on 
        s.id = t.id 
 where t.id is null
 LIMIT 0, 1

 drop table IDSeq

在SQL Server中:

declare @id int
declare @maxid int

set @id = 1
select @maxid = max(id) from tbl

create table #IDSeq
(
    id int
)

while @id < @maxid --whatever you max is
begin
    insert into #IDSeq values(@id)

    set @id = @id + 1
end

select TOP 1
    s.id 
from 
    #idseq s 
    left join tbl t on 
        s.id = t.id 
 where t.id is null

 drop table #IDSeq

答案 2 :(得分:0)

您可以使用min函数和where not exists子句获取它:

假设你的表是:

Table name: tbl
Number
-----
  1
  2
  3
  4
  6
  7

现在你可以说:

select (number+1) as gap
from tbl 
where number<(select max(number) from tbl)
and not exists (
          select  1
          from    tbl t 
          where   t.number = tbl.number + 1
        )
order by gap

输出:

gap
5

答案 3 :(得分:0)

首先,您需要知道没有理由找到IDENTITY列的差距并使用该

创建新记录

但如果您只是想知道答案,可以试试这个:

WITH C(id) AS(
    SELECT 1
    UNION
    SELECT 2
    UNION
    SELECT 3
    UNION
    SELECT 4
    UNION
    SELECT 6
    UNION
    SELECT 7
    UNION
    SELECT 8
)
SELECT TOP 1 id + 1
FROM C m
WHERE NOT EXISTS
        (
        SELECT NULL
        FROM C mm 
        WHERE mm.id = m.id + 1
        )
ORDER BY id