TSQL计数函数和明显缺少的NULL值

时间:2012-09-10 22:10:11

标签: sql database sql-server-2008 tsql count

根据MSDN,TSQL COUNT(*)函数包括结果中的任何NULL值,除非还使用了DISTINCT(来源:http://msdn.microsoft.com/en-us/library/ms175997.aspx

但是,在我的查询中,忽略NULL值。为了测试这个,我创建了一个小表并填充了一些数据:

CREATE TABLE tbl (colA varchar(1), colB varchar(10))
INSERT tbl VALUES
('Y', 'test1'),
('Y', 'test2'),
(null, 'test3'),
(null, 'test4'),
('N', 'test5')

然后我对它运行了以下2个查询:

SELECT count(*) FROM tbl
WHERE colA <> 'N'

SELECT DISTINCT colA FROM tbl
WHERE colA <> 'N'

两个结果都忽略NULL值。我分别得到2和'Y'作为结果。我不知道为什么会发生这种情况。有人可以告诉我吗?

在SQL小提琴中模拟的结果:http://sqlfiddle.com/#!3/8f00b/9

6 个答案:

答案 0 :(得分:5)

空虚很奇怪。

null <> 'N'评估为false null = 'N'也评估为false

您需要明确处理null:

SELECT count(*) FROM tbl
WHERE (colA <> 'N') or (colA is null)

答案 1 :(得分:2)

除了IS NULL之外的任何Null比较都将失败。因此Null ='N'和Null&lt;&gt; 'N'返回false。

如果你想要包含空值,你需要说

WHERE colA <> 'N' or colA IS NULL

答案 2 :(得分:2)

由于NULL未知,服务器不知道它的值是什么。但请尝试使用IS NULL

SELECT count(*) 
FROM tbl
WHERE colA <> 'N' or  
      colA IS NULL

SQLFiddle Demo

答案 3 :(得分:2)

declare @tbl as Table (colA varchar(1), colB varchar(10)) 
insert @tbl values 
  ('Y', 'test1'), ('Y', 'test2'), (null, 'test3'), (null, 'test4'), ('N', 'test5')
select * from @tbl

select
  count(*) as 'Rows', -- All rows.
  count(colA) as [colA Values], -- Rows where   colA   is not NULL.
  count(colB) as [colB Values],  -- Rows where   colB   is not NULL.
  count(distinct colA) as [Distinct colA], -- Number of distinct values in   colA .
  count(distinct colB) as [Distinct colB], -- Number of distinct values in   colB .
  -- NULL never equals anything, including another NULL.
  case when 42 = NULL then 'Yes' else 'Unknown' end as [Answer Is NULL?],
  case when NULL = NULL then 'Yes' else 'Unknown' end as [NULL = NULL],
  -- Use   is NULL   to explicitly check for   NULL .
  case when NULL is NULL then 'Yes' else 'Unknown' end as [NULL is NULL]
  from @tbl

答案 4 :(得分:2)

 select count(IsNull(colA,'')) as colA, count(colB) as colB from @tbl

也应该做的伎俩

答案 5 :(得分:1)

您还可以使用ISNULL功能:

SELECT count(*) 
FROM tbl
WHERE isnull(colA,'F') <> 'N' 

MSDN:http://msdn.microsoft.com/en-us/library/aa933210(v=sql.80).aspx