答案 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
相比,这有两个优点:
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查询并计算特定列的总和。