GAPSAND ISLANDS

寻找列中的gap.其实在inside sql server 2008中有专门的讨论。

create table test (id int primary key); go

insert into values (1),(2),(3),(4),(5),(6),(8),(9),(11),(12),(13),(14),(18),(19)

查找出结果为:

missingbefore missingafter

6                           8

9                           11

14                         18

以下为sql:

第一种方法使用了一个辅助表temp(tid int primarykey).在里面插入了一定量的数据。

WITH CTE AS
(
 SELECT
 TID 
 FROM
 temp WHERE TID<=
 (SELECT MAX(ID)FROM TEST)
)
,
CTE2 AS
(
SELECT * 
FROM CTE
WHERE TID NOT IN 
(
 SELECT ID FROM TEST 
)
),
CTE3 AS
(
SELECT 
ROW_NUMBER() OVER(ORDER BY T2.ID) AS ROWNO
,T2.ID
FROM CTE2 T1
JOIN TEST T2
ON
( T1.TID=T2.ID-1
OR T1.TID=T2.ID+1)
)
SELECT 
T.ID AS MISSINGAFTER,
T1.ID AS MISSINGBEFORE
FROM CTE3 T
JOIN CTE3 T1
ON T.ROWNO=T1.ROWNO-1
WHERE T.ROWNO%2=1
and T1.ROWNO%2=0

 

 WITH TT AS 
 (
 select  ROW_NUMBER() over(  order by cur.id asc) as rownumber,
    bef.id as bef_id,  
    cur.id as cur_id,  
    aft.id as aft_id        
  from test cur  
  left join test bef  
  on cur.id=bef.id+1  
  left join test aft  
  on cur.id=aft.id-1 
 )
 SELECT bf.cur_id as missing_after,  
        af.cur_id as missing_before   
 FROM TT as bf
 join TT as af on bf.rownumber=af.rownumber-1
 where af.cur_id-bf.cur_id>1; 

 

 

你可能感兴趣的:(SAN)