日期:2014-05-18  浏览次数:20380 次

能否做一个查询,找出表中连续数中短缺的数字。
有一个表,表中有一列,该列的值应该依次为1、2、3、4、...100,但是其中短缺了几个数,短缺的是什么数未知。能否做一个查询找出在最小数1和最大数100之间短缺的哪几个数。
例如,假如在1-100中,短缺了8、15,44、73,
该查询结果应为8、15,44、73。
不知道叙述清楚没有。

------解决方案--------------------
==============================================================
测试表数据
drop table testCSDN
create table testCSDN
(AUTOID int primary key IDENTITY(1,1), ColumnsValue int)


declare @i int
select @i=1
while @i <=100
begin
insert into testCSDN(ColumnsValue) Values(@i)
set @i=@i+1
end
==============================================================
--先创建一临时表,我是测试,所以结构与数据表相同
create table #temp
(AUTOID int primary key IDENTITY(1,1), ColumnsValue int)
--赋值
declare @i int
select @i=1
while @i <=100
begin
insert into #temp(ColumnsValue) Values(@i)
set @i=@i+1
end
--执行
select * FROM #temp WHERE AUTOID not in (select ColumnsValue from testCSDN)


PS:我也是头一次给别人写SQL,方法仅供参考,高手可能有更好的方法。
------解决方案--------------------
看错,改下
select * from (select top 100 (select count(1) from sysobjects where t.id> =id) as id from sysobjects t order by id) t where id not in (select 列名 from 表)
------解决方案--------------------
if object_id( 'tempdb..#tmp ') is not null
drop table #tmp
GO
----创建循环临时表
select top 100 id = identity(int,1,1) into #tmp from sysobjects,syscolumns
----创建测试数据
declare @t table(id int)
insert @t
select 1 union all
select 3 union all
select 5 union all
select 7 union all
select 9 union all
select 13

----查询
SELECT a.id + b.id as id FROM @t AS a
INNER JOIN #tmp AS b ON a.id + b.id < (select min(id) from @t where id > a.id)

----清除测试环境
drop table #tmp

/*结果
id
-----------
2
4
6
8
10
11
12
*/
------解决方案--------------------
错了,改下:
select IDs=nId+1 from tb
where nId <100 and not exists(select 1 from tb as t where t.nId=tb.nId+1)
union
select IDs=1 from tb
where not exists(select 1 from t where t.nId=1)
------解决方案--------------------
找一个有连续ID的表...

然后
selet id,count(id) from (select id from 你的表 union all select id from 有连续ID的表) having count(id)=1 就是缺的.