跨3个表的SQL计数

时间:2010-08-19 15:05:25

标签: tsql sql-server-2008 count

我有一个查询在有数据时工作正常,但在慈善表中没有任何内容时却没有。任何帮助都将非常感激。

SELECT  C.CategoryId
    , C.CategoryName
    , ISNULL(COUNT(CC.CharityId), 0) as CharityCount
    , C.IsDeleted
FROM    Charity.Categories C
LEFT JOIN Charity.CharityCategories CC on C.CategoryId = CC.CategoryId
LEFT JOIN Charity.Charities CH ON CC.CharityId = CH.CharityId
WHERE CH.IsApproved = 1 and CH.IsDeleted = 0
GROUP BY C.CategoryId, C.CategoryName , C.IsDeleted
Order By C.CategoryName

我基本上试图检索所有可用的Charity.Categories以及已批准和未删除的慈善机构的计数。

1 个答案:

答案 0 :(得分:4)

尝试更改它:

SELECT  C.CategoryId 
    , C.CategoryName 
    , ISNULL(COUNT(CC.CharityId), 0) as CharityCount 
    , C.IsDeleted 
FROM    Charity.Categories C 
LEFT JOIN Charity.CharityCategories CC on C.CategoryId = CC.CategoryId 
LEFT JOIN Charity.Charities CH ON CC.CharityId = CH.CharityId 
    AND CH.IsApproved = 1 and CH.IsDeleted = 0 
GROUP BY C.CategoryId, C.CategoryName , C.IsDeleted 
Order By C.CategoryName 

通过引用WHERE子句中的CH(Charities),可以设置为当这些值为NULL(即慈善机构中没有记录匹配)时,也会排除其他表中的数据。

出于这个原因,我通常会尽可能在join子句中包含所有约束/过滤器。