查询中的两个计数导致错误的结果

时间:2015-06-05 13:32:05

标签: sql sql-server

使用

SELECT table1.FullName,
  SUM(table2.Asp_PointsAwarded) AS 'Table2 Total Points', 
  table3.Name, 
  table4.Asp_PointsAwarded
FROM table1
LEFT JOIN table3 ON table1.ParentCustomerId = table3.AccountId
INNER JOIN table2 ON table1.ContactId = table2.Asp_SalemadebyId
INNER JOIN table4 ON table1.ContactId = table4.Asp_PointsAwardedToId
WHERE     (table3.asp_mimanagerid = '10CACCBD-70A7-DD11-9C65-001EC9B77038')
GROUP BY table1.FullName, table3.Name, table4.asp_pointsawarded
ORDER BY table1.FullName

我得到以下正确的结果。 89571已经正确总结:

John Doe - 89571 - Contoso - 500
John Doe - 89571 - Contoso - 750
John Doe - 89571 - Contoso - 2000
John Doe - 89571 - Contoso - 26302
John Doe - 89571 - Contoso - 61606

但是当我尝试使用下面的代码

来SUM table4.Asp_PointsAwarded
SELECT     table1.FullName, 
  SUM(table2.Asp_PointsAwarded) AS 'Table2 Total Points',
  table3.Name, 
  SUM(table4.Asp_PointsAwarded) AS 'Table4 Total Points'
FROM table1
LEFT JOIN table3 ON table1.ParentCustomerId = table3.AccountId
INNER JOIN table2 ON table1.ContactId = table2.Asp_SalemadebyId
INNER JOIN table4 ON table1.ContactId = table4.Asp_PointsAwardedToId
WHERE     (table3.asp_mimanagerid = '10CACCBD-70A7-DD11-9C65-001EC9B77038')
GROUP BY table1.FullName, table3.Name
ORDER BY table1.FullName

我得到以下

John Doe - 447855 - Contoso - 41568048

为什么会发生这种情况?看起来89571再次加起来5次,我不想发生。理想情况下,我想看到以下输出:

John Doe - 89571 - Contoso - 91158

1 个答案:

答案 0 :(得分:0)

对于左手表中的每一行,join重复右表中的所有匹配行。如果进行两次连接,则对于第一个表中的所有行,对于第二个表中的所有行,它将重复第三个表中的所有行。这意味着计数错了。

您可以在加入前通过求和来解决此问题:

SELECT  table1.FullName
,       sub1.sum_points
,       table3.Name
,       sub2.sum_points
FROM    table1
JOIN    table3
ON      table1.ParentCustomerId = table3.AccountId
JOIN    (
        SELECT  Asp_SalemadebyId
        ,       SUM(Asp_PointsAwarded) sum_points
        FROM    table2
        GROUP BY
                Asp_SalemadebyId
        ) sub1 
ON      table1.ContactId = sub1.Asp_SalemadebyId
JOIN    (
        SELECT  Asp_PointsAwardedToId
        ,       SUM(Asp_PointsAwarded) sum_points
        FROM    table4
        GROUP BY
                Asp_PointsAwardedToId
        ) sub2
ON      table1.ContactId = sub2.Asp_PointsAwardedToId
WHERE   table3.asp_mimanagerid = '10CACCBD-70A7-DD11-9C65-001EC9B77038')