我假设排序由 定义WeekNumber
,并且这是连续的,没有间隙。与其进行更新,不如只在选择期间执行计算(这样,您不必担心计算已过时):
declare @t table (WeekNumber int, Var1 int)
insert into @t (WeekNumber, Var1) values
(1, 10),
(2, 30),
(3, 80)
;with CarryOvers as (
select WeekNumber,Var1,CONVERT(decimal(38,4),Var1) as CarryOver from @t where WeekNumber=1
union all
select t.WeekNumber,t.Var1,CONVERT(decimal(38,4),t.Var1 + (0.2*co.CarryOver))
from @t t inner join CarryOvers co on t.WeekNumber = co.WeekNumber+1
)
select * from CarryOvers option (maxrecursion 0)
结果:
WeekNumber Var1 CarryOver
----------- ----------- ---------------------------------------
1 10 10.0000
2 30 32.0000
3 80 86.4000
UPDATE
版本:
declare @t table (WeekNumber int, Var1 int,CarryOver decimal(38,4))
insert into @t (WeekNumber, Var1) values
(1, 10),
(2, 30),
(3, 80)
;with CarryOvers as (
select WeekNumber,Var1,CONVERT(decimal(38,4),Var1) as CarryOver from @t where WeekNumber=1
union all
select t.WeekNumber,t.Var1,CONVERT(decimal(38,4),t.Var1 + (0.2*co.CarryOver))
from @t t inner join CarryOvers co on t.WeekNumber = co.WeekNumber+1
)
update t set CarryOver = co.CarryOver
from @t t inner join CarryOvers co on t.WeekNumber = co.WeekNumber
option (maxrecursion 0)
select * from @t
但我要重复一遍,我建议不要这样做,除非SELECT
在正常使用期间运行它是一个已证明的性能问题 - 现在表中的任何其他UPDATE
s 都需要UPDATE
在之后立即运行它,所以你增加了相当大的性能成本对于每个UPDATE
.
添加Brand
:
declare @t table (Brand char(1),WeekNumber int, Var1 int)
insert into @t (Brand,WeekNumber, Var1) values
('x',1, 10),
('x',2, 30),
('x',3, 80),
('y',1,40),
('y',2,50)
;with CarryOvers as (
select Brand,WeekNumber,Var1,CONVERT(decimal(38,4),Var1) as CarryOver from @t where WeekNumber=1
union all
select t.Brand,t.WeekNumber,t.Var1,CONVERT(decimal(38,4),t.Var1 + (0.2*co.CarryOver))
from @t t inner join CarryOvers co on t.WeekNumber = co.WeekNumber+1 and t.Brand = co.Brand
)
select * from CarryOvers
order by Brand,WeekNumber option (maxrecursion 0)