希望尝试在SQL Server中返回下面的数据集。我有2列TrailerPosition&分频器和期待也返回区域。区域将计算为从区域1开始,然后在divider = 1之后将更改为记录上的区域2.然后在Divider = 1的下一条记录之后变为3.下面的屏幕截图看起来像我要返回的列
如何在SQL Server中完成此操作?
以下测试数据:
declare @t table (TrailerPosition nvarchar(5),Divider bit);
insert into @t values ('01L',0),('01R',0),('02L',0),('02R',1),('03L',1),('03R',0),('04L',0),('04R',0),('05L',1),('05R',1),('06L',0),('06R',0),('07L',0),('07R',0),('08L',0),('08R',0),('09L',0),('09R',0),('10L',0),('10R',0),('11L',0),('11R',0),('12L',0),('12R',0),('13L',0),('13R',0),('14L',0),('14R',0),('15L',0),('15R',0);
答案 0 :(得分:4)
如果是2012+,窗口函数将非常适合
Select TrailerPosition
,Divider
,Zone = 1+sum(Flag) over (Order By TrailerPosition)
From (
Select *
,Flag = case when Lag(Divider,1) over (Order By TrailerPosition) =1 and Divider=0 then 1 else 0 end
From YourTable
) A
<强>返回强>
答案 1 :(得分:0)
因此,Zone = 1 +前一行的分频器值为0,前一行的分频器值为1.
<强>已更新强>
SELECT TrailerPosition, Divider,
(SELECT COUNT(*)
FROM @MyTable T1
WHERE (T1.TrailerPosition <= t0.TrailerPosition)
AND (T1.Divider = 0)
AND (SELECT Divider
FROM @MyTable t2
WHERE T2.TrailerPosition =
(SELECT MAX(T3.TrailerPosition)
FROM @MyTable T3
WHERE T3.TrailerPosition < T1.TrailerPosition)) = 1) + 1
AS Zone
FROM @MyTable t0