简体   繁体   English

从两个不同的表中添加总和值

[英]Adding sum values from two different tables

How can i achieve this.我怎样才能做到这一点。 T2 is linked with another table which contains order details like customer name, country and classification. T2 与另一个包含订单详细信息(如客户名称、国家/地区和分类)的表相关联。 They have an inner join.他们有一个内部连接。

T1 is linked to T2 only via order code and order item. T1 仅通过订单代码和订单项目链接到 T2。

在此处输入图片说明

Assuming that both tables report the same set of order numbers, we can try joining two subqueries each of which finds the sums in the respective tables:假设两个表都报告相同的一组订单号,我们可以尝试连接两个子查询,每个子查询在各自的表中找到总和:

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;

Note that the above is not necessarily an ideal approach, because a given order/item combination in one table might not appear in the other table.请注意,上述方法不一定是理想的方法,因为一个表中的给定订单/项目组合可能不会出现在另一个表中。 A better approach would be to start the query with a reference table containing all orders and items.更好的方法是使用包含所有订单和商品的参考表开始查询。 That failing, we could convert the above to a full outer join.失败了,我们可以将上面的转换为完整的外连接。

I think a simple approach is union all :我认为一个简单的方法是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;

This has two advantages over pre-aggregating and using join s:与预聚合和使用join相比,这有两个优点:

  1. It keeps all order/item pairs, even those that appear in one table.它保留所有订单/项目对,即使是出现在一张表中的那些。
  2. If you add a where claus to the outer query, SQL Server is likely to "project" that into the subqueries.如果向外部查询添加where子句,SQL Server 可能会将其“投射”到子查询中。

Try for bellow query also也尝试进行波纹管查询

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

if you have wanted the only sum from another table that time you have used select query and do the sum of a particular column.如果您当时想要来自另一个表的唯一总和,那么您已经使用了选择查询并计算了特定列的总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM