Search code examples
sqllagdifference

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


Good afternoon! I want to get the following result: to subtract the remainder of the difference that must be shipped. I try through the LAG function. It turns out, but somehow everything is crooked. Tell me how you can write it in SQL more elegantly.

enter image description here

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)

And the query:

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; 

Solution

  • My best guess is that you want cumulative sums:

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

    Here is a db<>fiddle.