SQL Server - using LAG in SUM of calculated field

时间:2018-02-01 18:04:50

标签: sql-server

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

1 个答案:

答案 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)