SQL查询计数 - 加入两个表并获得计数,即使它为0

时间:2014-12-16 15:24:39

标签: sql sql-server join count

好的,现在在SQL 2012中处理查询以加入两个表并获取计数。重要的是有多少公司与一家主要公司有关联。此列表存在于同一个表“联系人”中,并且它们全部连接为主要公司的ID在辅助公司中列为CompanyID。我可以得到一个计数,如果主要至少有一个辅助,但如果主要没有辅助我似乎得到一个计数,我需要显示该0值。这是我的SQL查询:

SELECT c.ID, c.Company, c.Category, COUNT(c1.ID) AS Secondaries
FROM Contact AS c INNER JOIN Contact AS c1 ON c.ID = c1.CompanyId
WHERE (c.MemberType = 'ORG_M') AND (c1.MemberType = 'ORG_M')
GROUP BY c.ID, c.Company, c.Category

当我这样做时,我会收到这些信息:

ID  Company       Category      Count
1   Company 1     RS_1          1
2   Company 2     RS_1          1
3   Company 3     RS_1          1
4   Company 4     RS_1          1

我缺少的是公司表中存在公司但没有与之挂钩的二级公司的0值。我怎么做到的?

1 个答案:

答案 0 :(得分:2)

改为使用outer join并将where条件移至join

SELECT c.ID, c.Company, c.Category, COUNT(c1.ID) AS Secondaries
FROM Contact AS c
    LEFT JOIN Contact AS c1 ON c.ID = c1.CompanyId AND c1.MemberType = 'ORG_M'
WHERE c.MemberType = 'ORG_M'
GROUP BY c.ID, c.Company, c.Category