使用这些查询:
Select P.productid, Sum(pr.quantity) AS PQuantity from Products p
join purchases pr on pr.Productid = p.productid
group by p.productid;
Select P.productid, Sum(s.quantity) AS SQuantity from Products p
join Sales s on s.Productid = p.productid
group by p.productid;
这是我的表格(购买和销售)中的内容,右边的是带分组的总和:
select p.productid, sum(pr.quantity) as PQuantity, sum(s.quantity) as SQuantity
from products p
join sales s on p.productid = s.productid
join purchases pr on p.productid = pr.productid
group by p.productid
但是当我加入三张桌子时会出现问题:
答案 0 :(得分:0)
你必须在加入前总结这些数字,如下所示:
select isnull(P.productid, S.productid), P.PQuantity, S.SQuantity
from
(
Select P.productid, Sum(pr.quantity) AS PQuantity from Products p
join purchases pr on pr.Productid = p.productid
group by p.productid
) P
full outer join
(
Select P.productid, Sum(s.quantity) AS SQuantity from Products p
join Sales s on s.Productid = p.productid
group by p.productid
) S on S.productid = P.productid