简体   繁体   English

如何在多个表的COUNT个汇总中计算零结果?

[英]How to count zero results in COUNT aggregate across multiple tables?

I have 3 example tables: 1. Person 我有3个示例表:1.人

PID         PNAME                         
----------- ------------------------------
111111111.  James Brock
222222222.  Dean Sampson
333333333.  Adam Klein
444444444.  Sam Toggle
  1. Company 公司

    CID CNAME CID CNAME


    1. Company A 公司A
    2. Company B 公司B
    3. Company C 公司C
    4. Company D 公司D
  2. Working 工作中

    PID CNAME PID CNAME


    1. Company B 公司B
    2. Company A 公司A
    3. Company A 公司A
    4. Company C 公司C

I want to show the # of employees at each company, including those that don't have any employees (ie: 0 of them) 我想显示每个公司的员工数量,包括没有员工的员工(即:0名员工)

So I have this so far: 所以到目前为止我有:

SELECT CNAME, COUNT(*) as EMPLOYEES
    FROM PERSON P, WORKING W, COMPANY C
    WHERE P.PID = W.PID
        AND W.CNAME = C.CNAME
    GROUP BY CNAME;

Which returns: 哪个返回:

CNAME       EMPLOYEES                         
----------- ------------------------------
Company A   2
Company B   1
Company C   1

Notice that Company D is missing 请注意,缺少公司D

I want this: 我要这个:

CNAME       EMPLOYEES                         
----------- ------------------------------
Company A   2
Company B   1
Company C   1
Company D   0

Is there an approach I can take to get the result I want? 我可以采取一种方法来获得想要的结果吗? All other examples I found online only use 2 tables to match. 我在网上找到的所有其他示例仅使用2个表进行匹配。

Never use commas in the FROM clause. 请勿FROM子句中使用逗号。 Always use proper, explicit JOIN syntax. 始终使用正确的显式JOIN语法。 Then, the LEFT JOIN would be obvious. 然后, LEFT JOIN将很明显。

SELECT C.CNAME, COUNT(W.PID) as EMPLOYEES
FROM COMPANY C LEFT JOIN
     WORKING W
     ON W.CNAME = C.CNAME
GROUP BY C.CNAME;

Note that the JOIN to PERSON is unnecessary. 请注意,不需要JOINPERSON You are only counting the people, not looking up their names. 您只是在计算人数,而不是查询他们的姓名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM