我有一张像
这样的表格Id Value
1 Start
2 Normal
3 End
4 Normal
5 Start
6 Normal
7 Normal
8 End
9 Normal
我必须输出像
这样的输出id Value
1 Start
2 Normal
3 End
5 Start
6 Normal
7 Normal
8 End
即。开始和放大之间的记录结束。 id为4&的记录9开始于&今后结束不在输出中。
如何以基于集合的方式执行此操作(SQLServer 2005)?
答案 0 :(得分:4)
加载表@t:
declare @t table(Id int,Value nvarchar(100));
insert into @t values (1,'Start'),(2,'Normal'),(3,'End'),(4,'Normal'),(5,'Start'),(6,'Normal'),(7,'Normal'),(8,'End'),(9,'Normal');
查询:
With RangesT as (
select Id, (select top 1 Id from @t where Id>p.Id and Value='End' order by Id asc) Id_to
from @t p
where Value='Start'
)
select crossT.*
from RangesT p
cross apply (
select * from @t where Id>=p.Id and Id<=Id_to
) crossT
order by Id
请注意,我假设没有重叠。结果:
Id Value
----------- ------
1 Start
2 Normal
3 End
5 Start
6 Normal
7 Normal
8 End