内连接总结所有行而不是1

时间:2013-11-05 16:35:57

标签: sql

我有2个表,一个包含收入数据,另一个包含帐户数据 - 帐户数据包含每个帐户多行......针对FactPlanNo 327865分配的收入值为65,000美元,这是我想要显示的,但是因为RefGPNRoleMapping表中有4行用于此帐户,它将$ 65,000乘以4

如何阻止这种情况发生,从而带来以下结果:

    AccountNumber     AccountName       Rev
    0123456           MyAccount         65000 (instead of 260,000)

我目前有这个查询:

   select
   b.AccountNumber,
   b.AccountName,
   sum(a.Revenue) as rev
   from mdfl.FactPlanNo a
   inner join xyz.RefGPNRoleMapping b on
   a.FactPlanNo = b.FactPlanNo
   where b.FactPlanNo = '327865'
   group by b.AccountNumber, b.AccountName

1 个答案:

答案 0 :(得分:0)

/* Revenue per "FactPlanNo" */
SELECT FactPlanNo
     , Sum(Revenue) As rev
FROM   mdfl.FactPlanNo
GROUP
    BY FactPlanNo

/* Make it a subquery and join to that! */
SELECT b.AccountNumber
     , b.AccountName
     , revenues.rev
FROM   (
        SELECT FactPlanNo
             , Sum(Revenue) As rev
        FROM   mdfl.FactPlanNo
        GROUP
            BY FactPlanNo
       ) As revenues
 LEFT
  JOIN xyz.RefGPNRoleMapping As b
    ON b.FactPlanNo = revenues.FactPlanNo
WHERE  b.FactPlanNo = '327865'