从列中的前一个值中减去当前行中其他值的差异

Subtract the difference from the others in the current row from the previous value in the column

下午好!我想得到以下结果:减去必须发货的差额的余数。我尝试通过 LAG 函数。事实证明,但不知何故,一切都是歪曲的。告诉我如何在 SQL 中更优雅地编写它。

CREATE TABLE TestTable(
[id] INT IDENTITY,
[productid] INT,
[name] NVARCHAR(256),
[ordered] DECIMAL(6,3),
[delivered] DECIMAL(6,3),
[remainder] DECIMAL(6,3));

INSERT INTO TestTable ([productid], [name], [ordered], [delivered], [remainder])
VALUES (712054, 'Product OSFNS', 253, 246.005, 13.255),
        (712054, 'Product OSFNS', 186, 183.63, 13.255),
        (712054, 'Product OSFNS', 196.8, 193.745, 13.255),
        (712054, 'Product OSFNS', 480, 477.025, 13.255)

以及查询:

WITH CTE_diff AS
(SELECT 
     T1.[id]
    ,T1.[productid]
    ,T1.[name]
    ,T1.[ordered]
    ,T1.[delivered]
    ,T1.[remainder]
    ,LAG(T2.[ordered] - T2.[delivered], 1, T1.[ordered] - T1.[delivered]) 
        OVER (ORDER BY T2.[productid])  as R
FROM TestTable T1 JOIN TestTable T2
    ON T1.id = T2.id - 1

UNION 

SELECT *
FROM (
    SELECT TOP(1)
         T1.[id]
        ,T1.[productid]
        ,T1.[name]
        ,T1.[ordered]
        ,T1.[delivered]
        ,T1.[remainder]
        ,LEAD(T2.[ordered] - T2.[delivered], 1, T1.[ordered] - T1.[delivered]) 
            OVER (ORDER BY T2.[productid]) as R
    FROM TestTable T1 JOIN TestTable T2
        ON T1.id = T2.id
    ORDER BY T1.id DESC
) as tbl)

SELECT * FROM CTE_diff; 

我最好的猜测是你想要累计和:

select tt.*,
       remainder + sum(delivered - ordered) over (partition by productid order by id) as net_amount
from testtable tt;

Here 是一个 db<>fiddle.