2013-04-10 69 views
0

我有以下查询:为什么我为计数得到0([现场])当空

Select [Field], count([Field]) as Counts 
from [Table_Name] 
group by [Field] 

结果如下所示:

[Field] [Counts] 
Type1 100 
Type2 100 
Type3 100 
Type4 100 
Null 0 

然而,当我在算键或任何其他字段比我分组的字段我得到[字段]空的行的实际数量。这是为什么?

Select [Field], count([Other]) as Counts 
from [Table_Name] 
group by [Field] 

结果:

[Field] [Counts] 
Type1 100 
Type2 100 
Type3 100 
Type4 100 
Null 100 

回答

3

那怎么COUNT作品。当您指定列NULL值从计算中消除。因为COUNTGROUP BY设置在同一列,所以您收到组的0组 - 您计算的所有值均为NULL,并且它们都被跳过。

你可以把它与下面的代码工作:

Select [Field], count(ISNULL([Field], 0)) as Counts 
from [Table_Name] 
group by [Field] 

或者,也许更简单:

Select [Field], count(*) as Counts 
from [Table_Name] 
group by [Field] 
+0

+1为解释......我无法用言语表达秒。 – 2013-04-10 22:30:42

0

你可能想用我的SQL Fiddle实验。

当前配置(你可以让你想要的任何改变)以下数据:

FIELD1 OTHER 
AA  (null) 
BB   O1 
BB   O2 
AA   A1 
(null)  N3 
(null) (null) 

以下查询包含了这个特殊的表中的所有3个计数选项:

SELECT [Field1], COUNT([Field1]) [Fields], 
       COUNT([Other]) [Others], 
       COUNT(*) [Records] 
FROM [Table1] 
GROUP BY [Field1] 

产生结果如下:

FIELD1 FIELDS OTHERS RECORDS 
(null)  0  1  2 
AA   2  1  2 
BB   2  2  2