表格数据
start end status
1000 1002 Y
1003 1020 Y
1021 1022 N
1023 1030 Y
1031 1040 Y
1041 1050 Y
1051 1052 N
1053 1100 Y
我想按如下方式对查询结果进行GROUP
start end status
1000 1020 Y
1021 1022 N
1023 1050 Y
1051 1052 N
1053 1100 Y
我尝试使用 CTE 递归,但它在大约 37500 次迭代后达到最大值。该表有数十万个元组。
最佳答案
不久前我在这个网站上找到了类似的解决方案。但是没有保存链接。归功于那个人。无论如何,这里有一个 sqlfiddle 来获得你想要的结果,使用未知人的解决方案......
http://sqlfiddle.com/#!18/3e6b1/12/0
它基本上涉及到多次自连接和自检查以获得我们想要的结果。
代码如下:
create table tab1(
id int identity(1,1) not null,
startn int not null,
endn int not null,
status char(1)
);
insert into tab1(
startn,
endn,
status
)
values
(1000, 1002, 'Y'),
(1003, 1020, 'Y'),
(1021, 1022, 'N'),
(1023, 1030, 'Y'),
(1031, 1040, 'Y'),
(1041, 1050, 'Y'),
(1051, 1052, 'N'),
(1053, 1100, 'Y')
;
设置
select
t1.startn,
min(t2.endn) as endn,
t1.status
from tab1 as t1
join tab1 as t2
on t1.startn <= t2.startn
and t1.status = t2.status
and not exists(
select
1
from tab1 as t3
where
t2.endn + 1 >= t3.startn
and t2.endn < t3.endn
and t2.status = t3.status
)
where
not exists(
select
1
from tab1 as t4
where
t1.startn > t4.startn
and t1.startn <= t4.endn + 1
and t1.status = t4.status
)
group by t1.startn, t1.status
查询
关于sql-server - 分组连续表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48411640/