简体   繁体   中英

find department with at least 2 employees

I need to make sql question which will show all departments with at least 2 people in it.

SELECT department.name
FROM department
INNER JOIN employee
ON department.id = employee.department_id
GROUP BY employee.id
HAVING COUNT(employee.id) >= 2;

It's not showing me anything with this query

I think you using GROUP BY on wrong column.
If you want to count employee in each department, then you need to GROUP BY department.id .

SELECT department.id, department.name, COUNT(employee.id) AS total_employee
FROM department
INNER JOIN employee
ON department.id = employee.department_id
GROUP BY department.id, department.name
HAVING COUNT(employee.id) >= 2;

Try this:

SELECT d.name
FROM department d
WHERE
    (SELECT COUNT(*) FROM employee e
    WHERE d.id = e.department_id) >= 2

In this way if you want to change your limit (instead of 2, another value) your query will work.

If you use INNER JOIN if you want, in the future all departments with no employees you can't use it.

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