根据上一行和相同的计算列计算列值

时间:2020-06-10 16:15:20

标签: sql tsql

我正在努力根据CalcVal1计算Val2

Calc = previous_row.Calc + previousr_row.Val1-previous_row.Val2

输入数据按Date排序。

预期输出:

+---------+--------+------------+------+
|  Val1   |  Val2  |    Date    | Calc |
+---------+--------+------------+------+
| 0,00    | 0,00   | 2016-01-01 |    0 |
| 1000,00 | 0,00   | 2020-01-01 |    0 |
| 0,00    | 0,00   | 2020-01-15 | 1000 |
| 0,00    | 500,00 | 2020-02-01 | 1000 |
| 0,00    | 300,00 | 2020-03-01 |  500 |
| 0,00    | 0,00   | 2020-03-15 |  200 |
| 0,00    | 200,00 | 2020-04-01 |  200 |
+---------+--------+------------+------+

已经尝试了LAG函数,成功从上一行获取数据,但是我无法从上一行获取Calc计算值:

LAG(Val1) OVER (ORDER By Date) - LAG(Val2) OVER (ORDER BY Date)

在现实世界中,我将添加PARTITION BY,但这是另一回事。想暂时保持简单。

更新: 受到他人的启发:

SUM(Val1) OVER(ORDER BY Data) - SUM(Val2) OVER(ORDER BY Data) - Val1 + Val2 AS Calc

虽然它可以计算适当的值,但这有效吗?

我正在使用最新的SQL Server 2019 / Azure SQL。

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找累积和函数:

select t.*,
       max(val1) over (order by date) - sum(val2) over (order by date)
from t;

答案 1 :(得分:1)

    ALTER FUNCTION calc (@lagDate DATE)
    RETURNS INT
    AS
    BEGIN
        IF @lagDate IS NULL
            RETURN 0

        DECLARE @r INT

        SELECT @r = isnull(lag(val1) OVER ( ORDER BY [date] ), 0) - 
                    isnull(lag(val2) OVER ( ORDER BY [date] ), 0) + 
                    dbo.calc(lag([date]) OVER ( ORDER BY [date] ))
        FROM dbo.ss
        WHERE [date] <= @lagDate

        RETURN @r
    END
    GO

  SELECT *
        ,dbo.calc([date]) calc
    FROM dbo.ss