SQL Sum()查询错误

时间:2015-11-22 06:22:18

标签: sql-server sql-server-2008 join

实际数据

使用这些查询:

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;

这是我的表格(购买和销售)中的内容,右边的是带分组的总和:

enter image description here

问题:

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

但是当我加入三张桌子时会出现问题:

  1. 产品
  2. 购买
  3. 销售
  4. enter image description here

1 个答案:

答案 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