我想要一个SQL查询: 我有号码列表,如果列表中没有遗漏号码,我想找出第一个丢失的号码,然后给我下一个可用的号码
例如我有一个列数据1,2,4,这意味着我需要三个缺少的数字,如果我有1,2,3,4那么我需要数字5.请帮助谢谢
答案 0 :(得分:2)
您可以使用此查询:
SELECT MIN(t1.Number) + 1 AS MissingNumber
FROM dbo.TableName t1
LEFT OUTER JOIN dbo.TableName t2
ON (t1.Number + 1 = t2.Number)
WHERE t2.Number IS NULL
然而,这是一场竞争条件,第一场胜利。通常你不应该填补空白。如果它是关键列,您可以使用IDENTITY列并自动增加。
答案 1 :(得分:0)
-- Note the +1, so to include the next number if the sequence is "complete",
-- And the isnull(,0) to handle the "empty table" case
declare @m as int = (select isnull(max(id), 0) + 1 from yourtable)
-- Sequence 1...@m of numbers
;with t as (
select 1 x
union all
select x + 1
from t
where x <= @m)
-- Find the minimum missing numebr
select min(x) from t where not exists (select 1 from yourtable where id = x)
yourtable
表是您想要找到缺失数字的表格,id
是您要查找缺失数字的列。