3

以下脚本应返回部门名称和这些部门中的员工人数,市场营销、执行和销售部门的员工人数为“0”,但返回的值不是“0”,而是“1”。我该如何纠正?

select Department, Departments.DepartmentID, count(*) as 'NumOfEmps' 
from Departments
left join Employees
on   Employees.DepartmentID = Departments.DepartmentID
group by Departments.DepartmentID,Department

在此处输入图像描述

4

2 回答 2

6

您不能在一个查询中完成所有操作。您需要一个子查询首先获取员工人数,然后使用汇总结果获取相关部门信息(姓名等):

SELECT Department, Departments.DepartmentID, t.NumOfEmps
FROM Departments
LEFT JOIN (SELECT DepartmentID, count(*) as 'NumOfEmps'
           FROM Employees
           GROUP BY DepartmentID) t
  ON t.DepartmentID = Departments.DepartmentID

我正在对您的架构做出一些假设,因为它没有列出。列名可能有点偏离,但这是一般的想法。希望能帮助到你。

于 2012-05-10T19:21:20.157 回答
5

不要使用Count(*)计数您想要计数的东西,即员工。

Count(*)计算整行。因为当你计算时,部门中的每个部门总是至少有一个记录(*)你总是会得到至少 1

SELECT d.Department, d.DepartmentID, count(e.EmployeeID)
FROM Departments d
    LEFT JOIN employees e
    ON d.DepartmentID = e.DepartmentID
GROUP BY 
 d.Department, d.DepartmentID

演示

于 2012-05-10T19:35:43.223 回答