我需要提出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;
它没有向我显示任何有关此查询的内容
答案 0 :(得分:3)
我认为您在错误的列上使用GROUP BY
如果您想计算每个部门的员工,那么您需要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;
答案 1 :(得分:1)
试试这个:
SELECT d.name
FROM department d
WHERE
(SELECT COUNT(*) FROM employee e
WHERE d.id = e.department_id) >= 2
这样,如果您想更改限制(而不是2,另一个值),您的查询就会有效。
如果您愿意,可以使用INNER JOIN
,将来所有没有员工的部门都不能使用它。