跨数据库表减去常量

balp4ylt  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(281)

我需要从不同行的值中减去另一个表中的值。例如,我的表格有:

ProductID | Warehouse | Locator | qtyOnHand
-------------------------------------------
100       | A         | 123     | 12
100       | A         | 124     | 12
100       | A         | 124     | 8
101       | A         | 126     | 6
101       | B         | 127     | 12

ProductID | Sold
----------------
100       | 26
101       | 16

结果:

ProductID | Warehouse | Locator | qtyOnHand | available
-------------------------------------------------------
100       | A         | 123     | 12        | 0
100       | A         | 123     | 12        | 0
100       | A         | 124     | 8         | 6
101       | A         | 126     | 6         | 0 
101       | B         | 127     | 12        | 12

该值只能从仓库a中的值中减去。我在用postgresql。非常感谢您的帮助!

mpgws1up

mpgws1up1#

如果我理解正确的话,您需要将总库存与第一个表中的累计金额进行比较。第一个表中的行似乎是按从大到小的顺序排列的。注:这是一种解释,与问题中的数据不完全一致。
使用 JOIN 将数据汇集在一起,然后进行累积和运算:

select t1.*,
       (case when running_qoh < t2.sold then 0
             when running_qoh - qtyOnHand < t2.sold then (running_qoh - t2.sold)
             else qtyOnHand
        end) as available
from (select t1.*,
             sum(qtyOnHand) over (partition by productID order by qtyOnHand desc) as running_qoh
      from table1 t1
     ) t1 join
     table2 t2
     using (ProductID)

相关问题