日期:2014-05-17 浏览次数:20552 次
;with t as
select fb,fe from tb
union all
select a.fb,b.fe from t a
left join tb b on a.fe=b.fa-1
select min(fa),fb from (
select fa,max(fb) fb
from t
group by fa
) a
group by fb
CREATE TABLE T
(
序号 int,
起号 int,
止号 int
)
INSERT INTO T
SELECT 1,1,4
UNION ALL
SELECT 2,7,9
UNION ALL
SELECT 3,5,6
UNION ALL
SELECT 4,11,13
UNION ALL
SELECT 5,14,20
--方案1
;WITH CTE
AS
(
SELECT A.*
FROM T A
WHERE NOT EXISTS(SELECT 1 FROM T WHERE 止号=A.起号-1)
UNION ALL
SELECT Y.序号,NULL,X.止号
FROM T X
JOIN CTE Y ON X.起号=Y.止号+1
)
SELECT 序号,起号=MIN(起号),止号=MAX(止号)
FROM CTE
GROUP BY 序号
/*
序号 起号 止号
1 1 9
4 11 20
*/
--方案2
;WITH CTE1
AS
(
SELECT A.序号,A.起号,连接序号=R