日期:2014-05-18  浏览次数:20543 次

三个表联合查询,COUNT出错。
SQL code
SELECT A.[pkID]
, A.[OrgName]
, COUNT(B.[pkID]) AS JoinCount
, COUNT(C.[pkID]) AS InfoCount
FROM [dbo].[WebSite_UMS_List_Org] A
LEFT JOIN [dbo].[WebSite_CMS_Info_Model_Work_Dictionary_Org] B
ON A.[pkID] = B.[OrgID] AND B.[flagStatus] = 0
LEFT JOIN [dbo].[WebSite_CMS_Info_Relation_Org] C
ON A.[pkID] = C.[OrgID] AND C.[flagStatus] = 0
WHERE A.[flagStatus] = 0
GROUP BY A.[pkID], A.[OrgName], A.[SortID]
ORDER BY A.[SortID]


A表:
SQL code
pkID    ParentID    SortID    OrgName        OrgNameAS    flagStatus
27    3        0    市统计局    市统计局    0
28    3        0    市农委        市农委        0
29    3        0    市人口计生委    市人口计生委    0
B表:
[code=SQL]pkID    OrgID    flagStatus
1    28    0


C表:
SQL code
pkID    InfoID    OrgID    flagStatus
1    234    28    0
2    123    28    0
3    456    28    0


查询结果,想要显示的是:
SQL code
pkID    OrgName        JoinCount    InfoCount
27    市统计局    0        0
28    市农委        1        3
29    市人口计生委    0        0


结果显示的是:
SQL code
pkID    OrgName        JoinCount    InfoCount
27    市统计局    0        0
28    市农委        3        3
29    市人口计生委    0        0


就是JoinCount里,1和3的区别。

------解决方案--------------------
COUNT(DISTINCT B.[pkID]) AS JoinCount