I have a need to calculate a running total based on the value of a field in a different column in a preceding row.
A simplified example would be
e.g.
Day Investment(A) Payments(B) Multiplier(C) Profit(D) TotalFund(E)
0 100 0 0 0 100
1 100 0 0.1 10 110
2 100 0 0.5 55 165
3 90 10 -0.2 -33 122
4 70 20 0.5 61 163
5 80 -10 0.1 16.3 189.3
So my table will contain columns Day, Investment(A), Payments(B) and Multiplier(C). Profit(D) is calculated as TotalFund(E) from previous day multiplied by Multiplier(C) for the current day TotalFund(E) is calculated as TotalFund(E) from previous day plus Profit(D) from current day minus Payments(B) from current day
I can't figure out how I can do this using LAG within a SUM
答案 0 :(得分:0)
我认为你不能用LAG
来计算它。以下是使用recursive CTE
with myTable as (
select * from
(values
(0,100,0,0)
,(1,100,0,0.1)
,(2,100,0,0.5)
,(3,90,10,-0.2)
,(4,70,20,0.5)
,(5,80,-10,0.1)
) t ([Day], [Investment(A)], [Payments(B)], [Multiplier(C)])
)
, rcte as (
select
*, [Profit(D)] = cast(0 as decimal(20,4)), [TotalFund(E)] = cast(100 as decimal(20,4))
from
myTable
where [Day] = 0
union all
select
b.[Day], b.[Investment(A)], b.[Payments(B)], b.[Multiplier(C)], cast(a.[TotalFund(E)] * b.[Multiplier(C)] as decimal(20,4))
, cast(a.[TotalFund(E)] + a.[TotalFund(E)] * b.[Multiplier(C)] - b.[Payments(B)] as decimal(20,4))
from
rcte a
join myTable b on a.[Day] + 1 = b.[Day]
)
select * from rcte
option (maxrecursion 0)