如何查询处某字段不连续的纪录
如何查询处某字段不连续的纪录,比如 记录字段值为1,5,6,7,查处2,3,4
--参考这个:
/*
显示编码连号--缺号表
*/
begin tran
--创建测试表
select top 100 id=identity(int,1,1)
into #tb from
(select top 100 id from syscolumns) a
,(select top 100 id from syscolumns) b
,(select top 100 id from syscolumns) c
--随机删除记录,产生缺号
delete from #tb where id in(select top 31 id from #tb order by newid())
--显示缺号表结果
select * from #tb
--连号临时表
--得到每个连号的开始编号
select id=identity(int,1,1),cast(id as int) as bid
into #tempa from #tb a
where not exists(select 1 from #tb where id=a.id-1)
--得到每个连号的结束编号
select id=identity(int,1,1),cast(id as int) as eid
into #tempb from #tb a
where not exists(select 1 from #tb where id=a.id+1)
/*
--显示连号--单独显示
select a.bid as 连号开始编号,b.eid as 连号结束编号
from #tempa a,#tempb b
where a.id=b.id
*/
--缺号临时表
--得到每个缺号的开始编号
select id=identity(int,1,1),cast(id+1 as int) as bid
into #temp1 from #tb a
where not exists(select 1 from #tb where id=a.id+1)
--得到每个缺号的结束编号
select id=identity(int,0,1),cast(id-1 as int) as eid
into #temp2 from #tb a
where not exists(select 1 from #tb where id=a.id-1)
--判断是否存在第一个编号,如果不存在,将它补充进开始缺号的缺号表
if not exists(select 1 from #tb where id=1)
begin
set identity_insert #temp1 on
insert into #temp1(id,bid) values(0,1)
end
/*
--显示缺号--单独显示
select a.bid as 缺号开始编号,b.eid as 缺号结束编号
from #temp1 a,#temp2 b
where a.id=b.id
*/
--显示连号--缺号表
select a.连号开始编号,a.连号结束编号,b.缺号开始编号,b.缺号结束编号
from (
select a.id,a.bid as 连号开始编号,b.eid as 连号结束编号
from #tempa a,#tempb b
where a.id=b.id
) a full join (
select a.id,a.bid as 缺号开始编号,b.eid as 缺号结束编号
from #temp1 a,#temp2 b
where a.id=b.id
) b on a.id=b.id
rollback tran

浙公网安备 33010602011771号