2015-06-05 36 views
1

使用兩項查詢導致不正確的結果

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 

然而,當我嘗試使用下面的代碼

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 

我得到總結table4.Asp_PointsAwarded以下

John Doe - 447855 - Contoso - 41568048 

任何想法,爲什麼發生這種情況?它看起來像89571已經加了5次,我不想發生。理想的情況是我想看到下面的輸出:

John Doe - 89571 - Contoso - 91158 
+0

您需要正確格式化您的代碼,並重新將其粘貼在 –

+2

,因爲你花asp_pointsawarded了GROUP BY的你總結重複行。 –

回答

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') 
+0

這工作完美。非常感謝您的詳細回答,您已經幫助我瞭解我做錯了什麼。 並且感謝適當的SQL代碼佈局的崩潰過程,在最好的時候我的可怕! – JimmieMaul