[英]Adding sum values from two different tables
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
相比,这有两个优点:
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.