如何汇总单个键的每一列的总和,然后将总和分配给另一个表中的值?

时间:2019-04-15 12:57:53

标签: sql oracle

我正在尝试更新一个表中的一列,以使其汇总与特定键相关联的另一张表中的所有值。我无法正确使用语法,也无法在网络上找到此问题的答案。

我尝试更改放置“ SUM”的位置,但是它不起作用。

代码如下:

UPDATE purchase_order
SET total = SUM(SELECT total FROM purchase_order_items
WHERE purchase_order_items.purchase_order_order_no = purchase_order.order_no));

这将导致purchase_order表中的“ total”列更新为purchase_order_items中每个表中order_no列键均匹配的每个条目中“ total”列的总和。

2 个答案:

答案 0 :(得分:2)

您应该在子查询中使用SUM函数,并将结果分配给主表。

UPDATE PURCHASE_ORDER
   SET TOTAL = (SELECT SUM(PURCHASE_ORDER_ITEMS.TOTAL)
                  FROM PURCHASE_ORDER_ITEMS
                 WHERE PURCHASE_ORDER_ITEMS.PURCHASE_ORDER_ORDER_NO =
                       PURCHASE_ORDER.ORDER_NO);

答案 1 :(得分:2)

您可以使用MERGE语句:

MERGE INTO purchase_order dst
USING (
  SELECT purchase_order_order_no,
         SUM( total ) AS total
  FROM   purchase_order_items
  GROUP BY purchase_order_order_no
) src
ON ( dst.order_no = src.purchase_order_order_no )
WHEN MATCHED THEN
  UPDATE SET total = src.total;