我有以下查询:
Select [Field], count([Field]) as Counts
from [Table_Name]
group by [Field]
结果如下所示:
[Field] [Counts]
Type1 100
Type2 100
Type3 100
Type4 100
Null 0
然而,当我指望一个Key或任何其他字段而不是我正在分组的字段时,我得到[Field] Null的实际行数。那是为什么?
Select [Field], count([Other]) as Counts
from [Table_Name]
group by [Field]
结果:
[Field] [Counts]
Type1 100
Type2 100
Type3 100
Type4 100
Null 100
答案 0 :(得分:3)
这就是COUNT
的工作方式。指定列NULL
时,将从计算中消除值。由于COUNT
与GROUP BY
设置在同一列上,因此0
群组会收到NULL
- 您计算的所有值均为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]
答案 1 :(得分:0)
您可能想要试验我的SQL Fiddle。
按照当前配置(您可以对所需的任何更改)进行以下数据:
FIELD1 OTHER
AA (null)
BB O1
BB O2
AA A1
(null) N3
(null) (null)
以下查询包含此特定表的所有三个COUNT个选项:
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