SQL COUNT(*)返回错误的答案

时间:2012-05-10 19:18:51

标签: sql

以下脚本应返回部门的名称和这些部门中的员工数量,营销部门,执行部门和销售部门的员工数为“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

enter image description here

2 个答案:

答案 0 :(得分: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

我对你的架构做了一些假设,因为它没有列出。列名可能有些偏差,但这是一般的想法。希望它有所帮助。

答案 1 :(得分: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

DEMO