从两个不同的表中求和值

时间:2019-12-22 07:55:53

标签: sql oracle

我该如何做到这一点。 T2与另一个表链接,该表包含订单详细信息,例如客户名称,国家/地区和分类。他们有内在的联系。

T1仅通过订购代码和订购商品链接到T2。

enter image description here

3 个答案:

答案 0 :(得分:1)

假设两个表都报告相同的订单号集,我们可以尝试将两个子查询合并在一起,每个子查询都可以在各自的表中找到总和:

SELECT
    t1.ORDER_NUM,
    t1.ORDER_ITEM,
    t1.PRODUCED + t2.PRODUCED AS PRODUCED
FROM
(
    SELECT ORDER_NUM, ORDER_ITEM, SUM(PRODUCED) AS PRODUCED
    FROM table1
    GROUP BY ORDER_NUM
) t1
INNER JOIN
(
    SELECT ORDER_NUM, ORDER_ITEM, SUM(NET_IN - NET_OUT) AS PRODUCED
    FROM table2
    GROUP BY ORDER_NUM
) t2
    ON t1.ORDER_NUM = t2.ORDER_NUM AND
       t1.ORDER_ITEM = t2.ORDER_ITEM
ORDER BY
    t1.ORDER_NUM,
    t1.ORDER_ITEM;

请注意,上面的方法不一定是理想的方法,因为一个表中的给定订单/项目组合可能不会出现在另一表中。更好的方法是从包含所有订单和项目的参考表开始查询。失败了,我们可以将上面的转换为完整的外部联接。

答案 1 :(得分:0)

我认为一种简单的方法是union all

select ordernum, orderitem, sum(produced) as produced
from ((select ordernum, orderitem, produced
       from table1
      ) union all
      (select ordernum, orderitem, netout
       from table2
      )
     ) t12
group by ordernum, orderitem;

与预聚合和使用join相比,这有两个优点:

  1. 它保留所有订单/商品对,即使是那些出现在一张桌子中的商品。
  2. 如果在外部查询中添加where子句,则SQL Server可能会将其“投影”到子查询中。

答案 2 :(得分:0)

也尝试下面的查询

select t1.order_num,t1.order_item,sum(t1.produced)+(select sum(net_in) from t2)-(select sum(t2.net_out) from t2)PRODUCED
from t1 
group by t1.order_num,t1.order_item

如果您当时想要使用另一个表的唯一总和,则可以使用select查询并计算特定列的总和。