Skip to content
Advertisement

Update next record based on last updated record

I’m struggling to find a solution to update the calculation in the same table based on last updated records order by select column.

I have tried LEAD & LAG, but can’t give complete solution of my problem.

Here is my table:
ID  PID  QTY INVQTY **Desired Result** Calculation
1   1    2   112    110                (112 - 2)
2   1    2   112    108                (110 - 2)
3   1    1   112    107                (108 - 1)
4   1    1   112    106                (107 - 1)
5   1    4   112    102                (106 - 4)
6   1    2   112    100                (102 - 2)
7   1    12  112    88                 (100 - 12)
8   1    5   112    83                 (88 - 5)
9   2    1   2      1                  (2 - 1)
10  2    2   2      -1                 (1 - 2)
11  2    3   2      -4                 (-1 - 3)

I tried below query but didn’t succeed.

select *,
(LAG(a.invqty - a.Qty, 0) OVER (PARTITION BY a.pid ORDER BY a.id)) - (LAG(a.Qty, 1, 0) OVER (PARTITION BY a.pid ORDER BY a.id))
from #RunTotalTestData a 
order by a.pid, a.id

I can use a while loop, but there are more than 50K records. I want to do it in the fastest possible way.

Advertisement

Answer

Hmmm . . . If you want a select, then you want a cumulative sum:

select rttd.*,
       (invqty -
        sum(qty) over (partition by pid order by id)
       ) as desired_result
from #RunTotalTestData rttd;

If you actually want an update (as the title to the question suggests), you can use this in an updatable CTE>

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement