你可以在图片中找到整个场景
提前谢谢我的SQL查询如下:
SELECT
a.item_code,
a.rep_code,
sum(t.sales_target),
sum(a.actual)
FROM sales_target t
JOIN sales_actual a
ON a.item_code = t.item_code AND a.rep_code = t.rep_code
GROUP BY
a.item_code,
a.rep_code
答案 0 :(得分:1)
您正在为每个商品代码/代表获得笛卡尔积,因此值是错误的。一种方法是使用union all
然后汇总:
select ta.item_code, ta.rep_code,
sum(ta.sales_target), sum(ta.actual)
from ((select item_code, rep_code, sales_target, 0 as actual
from sales_target t
) union all
(select item_code, rep_code, 0 as sales_target, actual
from sales_actual a
)
) ta
group by ta.item_code, ta.rep_code;