【问题标题】:Calculate running difference between two columns in Postgresql计算Postgresql中两列之间的运行差异
【发布时间】:2020-09-24 19:02:32
【问题描述】:

我有如下两个表中的数据

表 1:

Material |Ordr Qty 
---------|---------
abcd     |4253

表 2:

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

让我知道如何实现预期的输出。

【问题讨论】:

    标签: sql postgresql sum window-functions


    【解决方案1】:

    考虑一个窗口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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多