简体   繁体   English

寻找至少有2名员工的部门

[英]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. 我需要使sql问题,它将显示所有部门至少有2个人。

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. 我认为您在错误的列上使用了GROUP BY
If you want to count employee in each department, then you need to GROUP BY department.id . 如果要计算每个部门的员工,则需要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. 这样,如果您想更改限制(而不是2,另一个值),查询将起作用。

If you use INNER JOIN if you want, in the future all departments with no employees you can't use it. 如果需要,可以使用INNER JOIN ,将来所有没有员工的部门都将无法使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用子查询查找每个部门员工的平均工资,按年龄对部门内的员工进行排序 - Using sub-query find the average salary of employees for each department , order employees within a department by age MySQL查询以找到员工平均年龄最低的部门 - MySQL query to find the department with the lowest average age of employees SQL查询以查找属于特定部门的员工的姓名 - SQL query to find names of employees belonging to particular department 给定雇员和部门表找到缺少的部门ID - Given employees and departments tables find missing department id 查找至少从事过 2 个项目的员工 - Find employees who have worked on at least 2 projects Sql 按部门划分的员工人数 - Sql numbers of employees by department 查找 EMP 表中每个部门的“员工人数”和这些员工的姓名 - Find the 'count of employees' per department & name of those counted employees present in EMP table MySQL查询以查找同时也是其他部门的雇员的经理(不是经理) - MySQL query to find managers who are also employees (not managers) in (an)other department(s) 查询以查找与同事超过 x 次的员工及其部门对 - Query to find pairs of employees and their department who have been co-worker more than x times MYSQL 各部门工资前2名及部门平均工资 - MYSQL top 2 salaried employees in each department and average department salary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM