求和并加入sql

时间:2016-11-03 13:51:58

标签: sql postgresql

我不明白为什么我的解决方案无效。

我正在尝试按数据库中的部门计算员工数量。

有两个表:

CREATE TABLE DEPARTMENT
(
    NAME VARCHAR(32) NOT NULL,
    ID INT NOT NULL PRIMARY KEY
);

CREATE TABLE EMPLOYEE
(
    NAME VARCHAR(32) PRIMARY KEY NOT NULL,
    DEPARTMENT INT NOT NULL REFERENCES DEPARTMENT(ID)
);

我创建了一个视图来显示部门中的员工数量。

CREATE 
OR REPLACE VIEW VIEW_NB AS 
SELECT
   DEPARTMENT.NAME AS DEPARTEMENT,
   count(*) AS nb 
FROM
   DEPARTMENT 
   LEFT JOIN
      EMPLOYEE 
      ON DEPARTMENT.ID = EMPLOYEE.DEPARTMENT 
GROUP BY
   DEPARTMENT.ID,
   DEPARTMENT.NAME;
SELECT
   ADD_DEPARTMENT('FRANCE', 10);
SELECT
   ADD_DEPARTMENT('SPAIN', 100);
SELECT
   ADD_EMPLOYEE('JOSE', 10);

结果是

 departement | nb 
-------------+----
 FRANCE      |  1
 SPAIN       |  1

但它应该是

 departement | nb 
-------------+----
 FRANCE      |  0
 SPAIN       |  1

我理解使用左连接的必要性。 但是,我的观点是每个部门至少有1名员工,即使他们没有员工。

我错过了什么吗?如果是的话?

3 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT DEPARTMENT.NAME AS DEPARTEMENT, count(EMPLOYEE.DEPARTMENT) AS nb
FROM DEPARTMENT
LEFT JOIN EMPLOYEE
ON DEPARTMENT.ID = EMPLOYEE.DEPARTMENT
GROUP BY DEPARTMENT.ID, DEPARTMENT.NAME;

您获得1作为计数的原因是因为您使用了*,这意味着 - 无论数据如何,都将任何记录计为1。 COUNT()默认忽略NULL,因此您只需在其中提供一个右(详细)表格列。

答案 1 :(得分:1)

更改第一行

SELECT DEPARTMENT.NAME AS DEPARTEMENT, count(*) AS nb
FROM DEPARTMENT
LEFT JOIN EMPLOYEE
ON DEPARTMENT.ID = EMPLOYEE.DEPARTMENT
GROUP BY DEPARTMENT.ID, DEPARTMENT.NAME;

SELECT DEPARTMENT.NAME AS DEPARTEMENT, count(EMPLOYEE.DEPARTMENT) AS nb
                                              ^^^^^^^^^^^^^^^^^^

答案 2 :(得分:1)

您需要计算"外部"的行数。表。由于聚合忽略NULL值,因此employee表中将忽略那些在count()表中没有匹配的行:

SELECT department.name AS departement,
       count(employee.department) AS nb
FROM department
  LEFT JOIN employee ON department.id = employee.department
GROUP BY department.id,
         department.name;