sample
declare @a table(Account int) insert into @a values(1 ) insert into @a values(2 ) insert into @a values(3 ) insert into @a values(4 ) insert into @a values(9 ) insert into @a values(10 ) insert into @a values(11 ) insert into @a values(20 ) --缺失的最小ID号 SELECT CASE WHEN NOT EXISTS(SELECT * FROM @a WHERE Account = 1) THEN 1 ELSE MIN(Account) + 1 END FROM @a AS A WHERE NOT EXISTS (SELECT * FROM @a AS B WHERE B.Account = A.Account + 1) --缺失的最大ID号 SELECT CASE WHEN NOT EXISTS(SELECT * FROM @a WHERE Account = 1) THEN 1 ELSE MAX(Account) - 1 END FROM @a AS A WHERE NOT EXISTS (SELECT * FROM @a AS B WHERE B.Account = A.Account - 1)
返回结果: 缺失最小值:5 缺失最大值:19
思路:将原表数据值与值+1/-1对比,找出缺失的相邻的值,然后条件“如果不存在最小值1则赋于值为1,要不周赋于缺失值表的最小(+1),最大(-1)