带有Count,Group By,Where和Join的SQL Server SELECT

时间:2012-05-27 17:45:51

标签: sql-server-2008 null count group-by where

我以前在SQL Server中创建了这个SELECT命令,需要计算每个Department包含的Employees数量。 这是我用过的:

SELECT Departments.Description AS [Department], COUNT(Employees.ID) AS [Employees]
FROM Employees 
RIGHT JOIN Departments ON
Employees.DepartmentID = Departments.ID 
GROUP BY Departments.Description

它工作正常(即使没有员工也显示部门)。

现在,我想通过以下过滤器只计算当前正在工作的员工:

WHERE Employees.JobEndDate = null

我试过这样做:

SELECT   Departments.Description AS [Department], COUNT(Employees.ID) AS [Employees] 
FROM Employees 
RIGHT JOIN Departments ON
Employees.DepartmentID = Departments.ID 
WHERE Employees.JobEndDate = NULL 
GROUP BY Departments.Description

但现在我没有结果。 知道我做错了吗?

谢谢:) Mitsy。

2 个答案:

答案 0 :(得分:4)

测试字段返回值是NULL是否不是通过相等的=符号执行,而是IS运算符

= null

不起作用,而是写:

Employees.JobEndDate IS NULL

答案 1 :(得分:0)

SELECT Departments.Description AS [Department], COUNT(Employees.ID) AS [Employees] FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.ID WHERE Employees.JobEndDate = IS NULL GROUP BY Departments.Description