SELECT COUNT返回0

时间:2015-09-01 12:25:29

标签: sql

有表格Departments

CREATE TABLE Departments
(
    id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    name  nvarchar(100) NOT NULL,
    parentDepId int
);

enter image description here

我需要计算parentDepId = NULL的行数,但我的查询每次都返回零。

SELECT COUNT(id) as DepartmentsCount
from Departments
WHERE parentDepId = NULL;

它出了什么问题?

3 个答案:

答案 0 :(得分:7)

您需要使用IS NULL

SELECT COUNT(id) AS DepartmentsCount FROM Departments 
 WHERE parentDepId IS NULL

这是与NULL比较的唯一方法(其他运算符不起作用)。

答案 1 :(得分:2)

SELECT COUNT(Isnull(id,1)) AS DepartmentsCount
 FROM Departments 
 WHERE parentDepId IS NULL

答案 2 :(得分:2)

我使用语法where Column is null。与等号的比较似乎是错误的