首页 > 数据库技术 > 详细

Sql Server间断与孤岛

时间:2020-12-01 13:55:49      阅读:53      评论:0      收藏:0      [点我收藏+]

创建测试表

if OBJECT_ID(tempdb..#test) is not null
  drop table #test
create table dbo.#test
(
seqval int not null constraint pk_#seqval primary key
);
insert into dbo.#test(seqval)values
(2),(3),(11),(12)--,(12)
,(13),(27),(33),(34),(35),(42);

查询间断

select bb.seqval+1 start, 
  (select MIN(cc.seqval)-1 from #test cc where cc.seqval>bb.seqval) end
from #test bb
where not exists
(
select * from #test cc
where bb.seqval+1=cc.seqval
)
and bb.seqval<(select MAX(seqval) from #test)

查询结果:

技术分享图片

 

 查询孤岛

;with startCte as
(
select ROW_NUMBER() over(order by bb.seqval)rn,bb.seqval startPoint
from #test bb
where not exists
(select * from #test cc where bb.seqval-1=cc.seqval)
)
,endCte as
(
select ROW_NUMBER() over(order by bb.seqval)rn,bb.seqval endPoint
from #test bb
where not exists
(select * from #test cc where bb.seqval+1=cc.seqval)
)
select s.startPoint,e.endPoint from startCte s 
  inner join endCte e on s.rn=e.rn

运行结果:

技术分享图片

 

Sql Server间断与孤岛

原文:https://www.cnblogs.com/tomorrow0/p/14067463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!