我有2个员工表(id,first_name,last_name,salary,department_id_和department(id,name))我希望显示每个部门的员工人数。 我在这里有这个问题:
SELECT department.name, COUNT(*) AS 'employees_number'
FROM department
LEFT JOIN employees
ON employees.department_id = department.id
GROUP BY department.id, department.name;
但是出于某种原因,在我没有人的部门中,它会将一些员工显示为1.知道为什么会这样吗?
答案 0 :(得分:0)
使用外部联接时,如果找不到外部表中的匹配项,则仍会得到结果行。只有所有员工列值为空。
因此,您不想对记录进行计数,而是要计算匹配的记录,即找到员工且其数据不为空的位置。因此,计算employee表中的列(计算列或表达式时不计算空值)。例如。使用COUNT(e.department_id)
或COUNT(e.id)
:
SELECT d.name, COUNT(e.id) AS employees_number
FROM department d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name;
我更喜欢的是在加入之前聚合/计数。查询看起来有点复杂,但在将来的查询更改中不太容易出错:
SELECT d.name, COALESCE(e.how_many, 0) AS employees_number
FROM department d
LEFT JOIN
(
SELECT department_id, COUNT(*) AS how_many
FROM employees
GROUP BY department_id
) e ON e.department_id = d.id;
由于它只是您想要的一个聚合列,您可以将子查询移动到SELECT
子句,从而获得更简单的查询:
SELECT
d.name,
(
SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.id
) AS employees_number
FROM department d;
答案 1 :(得分:0)
使用SUM
代替COUNT
也可以为您提供所需内容:
SELECT
department.name,
SUM(CASE WHEN employees.id IS NOT NULL THEN 1 ELSE 0 END) AS 'employees_number'
FROM department
LEFT JOIN employees
ON employees.department_id = department.id
GROUP BY department.id, department.name;