2013-04-10 37 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