从具有重复项的列中减去

时间:2017-02-28 02:13:04

标签: sql sql-server join

所以我需要从我的"消费"中减去交付的数量。表格来自" qitems"表。但是,有重复的项目,它只为每个项目减去一次。我该怎么办?我附上了表格的截图。在此先感谢您的帮助!

Update qi
Set qi.QtyOnHand = (qi.QtyOnHand - c.delqty)
From qitem qi
Inner Join Consuming c
on qi.itemname = c.itemname

1 个答案:

答案 0 :(得分:0)

我假设您正在使用SQL Server,基于语法。无论数据库如何,这个想法都是一样的。您需要在进行更新之前进行聚合:

Update qi
    Set qi.QtyOnHand = (qi.QtyOnHand - c.delqty)
    From qitem qi Inner Join
         (select c.itemname, sum(c.delqty) as delqty
          from Consuming c
          group by c.itemname
         ) c
         on qi.itemname = c.itemname;