我假定排序是由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
現在需要此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)
您可以通過第一個選擇stmnt的最後一個值,其中u得到最後carry_over_Value然後插入或更新 –