[英]Calculate running difference between two columns in Postgresql
我有兩個表中的數據如下
表格1 :
Material |Ordr Qty
---------|---------
abcd |4253
表二:
Material | Stck Qty
---------|---------
abcd |1000
abcd |2000
abcd |2000
預期輸出:
Material |Ordr Qty |Stck Qty |Column D
---------|---------|---------|---------
abcd |4253 |1000 |3253
abcd |4253 |2000 |1253
abcd |4253 |2000 |-747
D列的邏輯就像
4253-1000 = 3253
3253-2000 = 1253
1253-2000 = -747
LAG(ordr qty - stck qty,1,0)over (ORDER BY material)-stck qty
我正在嘗試高於 LAG 功能並低於輸出
abcd 4253 1000 -1000
abcd 4253 2000 1253
abcd 4253 2000 253
讓我知道如何實現預期的輸出。
考慮一個窗口sum()
而不是lag()
:
select t1.*, t2.stck_qty,
t1.ordr_qty - sum(t2.stck_qty) over(partition by material order by t2.id)
from t1
inner join t2 using(material)
order by material, t2.id
為了獲得穩定的結果,您需要一列來定義t2
中行的順序:我假設id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.