我将 int 数据类型列为否,并希望找到表中缺少的那些编号。
例如:1,2,3,7,8,9
答案 = 4,5,6
提前致谢。
我将 int 数据类型列为否,并希望找到表中缺少的那些编号。
例如:1,2,3,7,8,9
答案 = 4,5,6
提前致谢。
就在普通的sql中:
SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
FROM sequence AS a, sequence AS b
WHERE a.id < b.id
GROUP BY a.id
HAVING start < MIN(b.id)
你可以在Sqlfiddle上试试
尝试关注 -
DECLARE @TABLE TABLE (NUM INT)
INSERT INTO @TABLE
VALUES
(1)
,(2)
,(3)
,(7)
,(8)
,(9)
DECLARE @MIN INT
DECLARE @MAX INT
SELECT @MIN = MIN(NUM) + 1, @MAX = MAX(NUM) - 1 FROM @TABLE
CREATE TABLE #TMP (FIELD_NO INT)
WHILE @MIN <= @MAX
BEGIN
IF NOT EXISTS (SELECT * FROM @TABLE WHERE NUM = @MIN)
INSERT INTO #TMP (FIELD_NO) VALUES (@MIN)
SET @MIN = @MIN + 1
END
SELECT * FROM #TMP
DROP TABLE #TMP
您可以使用数字表
在这里,我使用master..spt_values
具有范围的0-2047
. 您可以将其替换为您自己的具有足够值的数字表。
declare @T table
(
Number int
);
insert into @T values (1),(2),(3),(7),(8),(9);
with MinMax as
(
select min(Number) as MinNumber,
max(Number) as MaxNumber
from @T
),
Number as
(
select N.Number
from master..spt_values as N
inner join MinMax as MM
on N.number between MM.MinNumber and MM.MaxNumber
where N.type = 'P'
)
select Number
from Number as N
where not exists
(
select *
from @T as T
where T.Number = N.number
)
order by N.number