只是爲了好玩,這個方法會生成並執行一些動態SQL。
Declare @YourTable table (Date date,Returns decimal(18,9))
Insert Into @YourTable values
('11/1/2016', 0.000542159),
('11/2/2016', -0.001629094),
('11/3/2016', 0.000568779),
('11/4/2016', -0.001246407),
('11/7/2016', 0.000795611),
('11/8/2016', 0.000663507),
('11/9/2016', -0.000254819)
Declare @SQL varchar(max) = '>>>'
Select @SQL = @SQL+String
From (
Select String=concat(',(|',Date,'|,',Returns,',',Stuff((Select '*' + cast(1.0+Returns as varchar(25))
From @YourTable
Where Date<=A.Date
For XML Path ('')),1,1,'') ,')')
From @YourTable A
) A
Select @SQL = 'Select * From (values '+replace(replace(@SQL,'|',''''),'>>>,','')+') A(Date,Returns,Final)'
Exec(@SQL)
返回
Date Returns Final
2016-11-01 0.000542159 1.000542159
2016-11-02 -0.001629094 0.998912182
2016-11-03 0.000568779 0.999480342
2016-11-04 -0.001246407 0.998234583
2016-11-07 0.000795611 0.999028789
2016-11-08 0.000663507 0.999691652
2016-11-09 -0.000254819 0.999436911
生成的SQL看起來像這樣
Select Date,Returns,Final=cast(Final as decimal(18,9))
From (values ('2016-11-01', 0.000542159,1.000542159)
,('2016-11-02',-0.001629094,0.998370906*1.000542159)
,('2016-11-03', 0.000568779,0.998370906*1.000542159*1.000568779)
,('2016-11-04',-0.001246407,0.998370906*0.998753593*1.000542159*1.000568779)
,('2016-11-07', 0.000795611,0.998370906*0.998753593*1.000542159*1.000568779*1.000795611)
,('2016-11-08', 0.000663507,0.998370906*0.998753593*1.000542159*1.000568779*1.000663507*1.000795611)
,('2016-11-09',-0.000254819,0.998370906*0.998753593*0.999745181*1.000542159*1.000568779*1.000663507*1.000795611)
) A(Date,Returns,Final)
所以你想要運行總計? – scsimon
更正同一表中不同帳戶組合的運行總額。 – user1143726