如何使用COUNT()和GROUP BY来显示每个部门的员工数量

时间:2017-09-21 18:28:02

标签: mysql sql group-by count

请考虑两个表 - 员工和部门

Employee:
EmployeeID
Name
DeptID

Department:
DepartmentID
DeptName
LocID

Employee.DeptID is a foreign key to Department.DepartmentID

如何显示所有部门(部门名称)的列表以及每个部门的员工数量?输出应如下所示:

DepartmentName         Number of employees
Accounts               30
HR                     24
Production             400
Sales/Marketing        250

etc...

2 个答案:

答案 0 :(得分:1)

使用GROUP BY

 SELECT d.deptID, count(e.deptID)
 FROM Department d
 LEFT JOIN Employee e ON d.DeptID = e.DeptID
 GROUP BY d.deptId

LEFT JOIN用于包含没有员工的部门。

答案 1 :(得分:1)

  

SELECT DeptName AS DepartmentName,COUNT(EmployeeID)AS NumberOfEmployees FROM Employee INNER JOIN Department ON DeptID = DepartmentID GROUP BY DepartmentID