[英]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.我正在努力寻找一种解决方案,根据 select 列的最后更新记录顺序来更新同一表中的计算。
I have tried LEAD
& LAG
, but can't give complete solution of my problem.我已经尝试过
LEAD
& LAG
,但无法完全解决我的问题。
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.我可以使用 while 循环,但有超过 50K 的记录。 I want to do it in the fastest possible way.
我想以最快的方式做到这一点。
Hmmm.嗯。 .
. .
. If you want a
select
, then you want a cumulative sum:如果你想要一个
select
,那么你想要一个累积和:
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>如果您确实想要
update
(正如问题的标题所暗示的那样),您可以在可更新的 CTE 中使用它>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.