SQL计数和分组不返回0的计数

时间:2017-04-11 14:20:59

标签: mysql sql count group-by

在我的情况下,我有一个Employee表和一个Department表。大多数部门都有员工,但是有一些部门没有员工。

我正在努力提升所有部门,并将大多数员工排除在外。

我已经尝试了INNER JOINLEFT JOIN,但似乎仍无法得到我想要的内容。

SELECT COUNT(Department.DEPT_ID) as total, Department.Name
FROM Department
  INNER JOIN Employee
    ON Department.DEPT_ID = Employee.DEPT_ID
GROUP BY Department.Name
ORDER BY total desc, Department.NAME asc;

但是,这不包括任何零雇员的部门。我也尝试过:

SELECT Department.NAME, IFNULL(COUNT(Department.DEPT_ID), 0) as total
FROM Department
  LEFT JOIN Employee
    ON Employee.DEPT_ID = Department.DEPT_ID
GROUP BY Department.NAME 
ORDER BY total desc, Department.NAME asc;

但这一次,对于零雇员的任何部门,它将其值设置为1,而不是0,这让我感到困惑。

我做错了什么?

编辑:@vkp的正确解决方案是:

SELECT Department.NAME, IFNULL(COUNT(Employee.DEPT_ID), 0) as total
FROM Department
  LEFT JOIN Employee
    ON Employee.DEPT_ID = Department.DEPT_ID
GROUP BY Department.NAME 
ORDER BY total desc, Department.NAME asc;

1 个答案:

答案 0 :(得分:0)

SELECT d.deptname,CASE WHEN e.total IS NULL THEN 0 ELSE e.total END AS total
  FROM dept d
  LEFT JOIN 
       (
         SELECT deptid,COUNT(*) AS total
           FROM emp
         GROUP BY deptid
        ) e
    ON d.deptid = e.deptid
ORDER BY CASE WHEN e.total IS NULL THEN 0 ELSE e.total END DESC;