简体   繁体   中英

Sql numbers of employees by department

I have 2 tables employees(id, first_name, last_name, salary, department_id_ and department(id, name) and I want to show number of employees in each department.

I have this question here:

SELECT department.name, COUNT(*) AS 'employees_number'
FROM department
LEFT JOIN employees
ON employees.department_id = department.id
GROUP BY department.id, department.name;

But for some reason, in departments where I have no people, it shows a number of employees as 1. Any idea why this is happening?

With an outer join you still get a result row when no match in the outer table is found. Only all employee column values are null then.

So rather than count the records, you want to count matched records, ie where an employee was found and its data is not null. So Count a column in the employee table (nulls are not counted, when counting a column or expression). Eg use COUNT(e.department_id) or 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;

What I prefer though, is to aggregate/count before joining. The query looks a bit more complicated, but is less prone to errors on future query changes:

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;

As it's one aggregated column only you want, you can move the subquery to your SELECT clause and get thus a simpler query:

SELECT 
  d.name,
  (
    SELECT COUNT(*)
    FROM employees e
    WHERE e.department_id = d.id
  ) AS employees_number
FROM department d;

Using SUM instead of COUNT also can give you what you want:

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;

SQL Fiddle: http://sqlfiddle.com/#!9/8b8976/1

select department.name, count(employee.id) as co from
department left join employee on
department.id = employee.dept_id group by department.name
order by co desc, department.name asc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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