当JOIN没有返回值时,将COUNT检索为0

时间:2016-08-03 07:31:14

标签: sql sql-server-2012

我有以下表格

性别

+----+-------------+
| ID | Description |
+----+-------------+
|  1 | M           |
|  2 | F           |
+----+-------------+

+----+-------------------+
| ID |  DepartmentName   |
+----+-------------------+
|  1 | Application       |
|  2 | Change Management |
|  3 | Infrastructure    |
+----+-------------------+

员工

+----+----------+----------+-------------+--------------+
| ID |   Name   | GenderID | StaffNumber | DepartmentID |
+----+----------+----------+-------------+--------------+
|  1 | Stephen  |        1 | SC001       |            1 |
|  2 | Jacob    |        1 | SC002       |            1 |
|  3 | Maria    |        2 | SC003       |            1 |
|  4 | Valerie  |        2 | SC004       |            1 |
|  5 | Herman   |        1 | SC005       |            3 |
|  6 | Trevor   |        1 | SC006       |            3 |
|  7 | Mark     |        1 | SC007       |            2 |
|  8 | Hendrick |        1 | SC008       |            2 |
+----+----------+----------+-------------+--------------+

我想了解按部门分组的员工总数。性别。如果部门不存在性别,我仍希望显示性别,并将0作为计数。

我尝试了这个SQL,但它没有找到我想要的东西:

SELECT
    e.DepartmentID,
    e.GenderID,
    COUNT(e.ID) AS TotalEmp
FROM
    Employee e
        RIGHT OUTER JOIN Gender g
            ON e.GenderID = g.ID
GROUP BY
    e.DepartmentID,
    e.GenderID
ORDER BY 
    e.DepartmentID,
    e.GenderID

当前结果

+--------------+----------+----------+
| DepartmentID | GenderID | TotalEmp |
+--------------+----------+----------+
|            1 |        1 |        2 |
|            1 |        2 |        2 |
|            2 |        1 |        2 |
|            3 |        1 |        2 |
+--------------+----------+----------+

预期结果

+--------------+----------+----------+
| DepartmentID | GenderID | TotalEmp |
+--------------+----------+----------+
|            1 |        1 |        2 |
|            1 |        2 |        2 |
|            2 |        1 |        2 |
|            2 |        2 |        0 |
|            3 |        1 |        2 |
|            3 |        2 |        0 |
+--------------+----------+----------+

1 个答案:

答案 0 :(得分:5)

试试这个:

   select d.DepartmentID,g.ID, COUNT(e.ID) AS TotalEmp
   from Gender g
   cross join Department d
   left join Employee e on e.genderid=g.id and e.departmentid=e.DepartmentID
   group by d.DepartmentID,g.id;