Sql server 在SQLServer2005(基于集合的方法)中查找范围之间的值?
我有一张像这样的桌子Sql server 在SQLServer2005(基于集合的方法)中查找范围之间的值?,sql-server,sql-server-2005,tsql,Sql Server,Sql Server 2005,Tsql,我有一张像这样的桌子 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 i、 e.开始和结束之间的记录。id为4和9的记录在开始和结束之外,因此输出中不存在 如何以基于
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
i、 e.开始和结束之间的记录。id为4和9的记录在开始和结束之外,因此输出中不存在
如何以基于集合的方式执行此操作(SQLServer2005)?加载表@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
加载一个表@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