Select minimum number from column which not exist

我与影子孤独终老i 提交于 2019-12-08 12:00:30

问题


I have in my column (id) values  
                               4
                               5
                               10

I want to choose minimum nubmer which not exists. Example value 1 then 2 then 3 and then 6.....

i'm trying this code

IF not EXISTS(SELECT min(id) from table1) select...

回答1:


Create a numbers table in your database, then it's easy:

SELECT MIN(Numbers.n) As MinMissingId
FROM [Numbers] 
WHERE NOT EXISTS
(
    SELECT 1 FROM dbo.TableName t WHERE Numbers.n = t.ID
)

Here's a small script that creates the table copied from Aaron's article:

SELECT TOP (1000000) n = CONVERT(INT, ROW_NUMBER() OVER (ORDER BY s1.[object_id]))
INTO dbo.Numbers
FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2
OPTION (MAXDOP 1);

CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers(n)
-- WITH (DATA_COMPRESSION = PAGE)
;



回答2:


You can find the first row where there does not exist a row with Id + 1.

Try this.

SELECT TOP 1 t1.Id+1 as ID
 FROM table t1
 WHERE NOT EXISTS(SELECT * FROM table t2 WHERE t2.Id = t1.Id + 1)
ORDER BY t1.Id;

Check this.. Online Demo HERE



来源:https://stackoverflow.com/questions/38521744/select-minimum-number-from-column-which-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!