2009-11-12 30 views

回答

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 
相關問題