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

但是,当我依靠键或任何其他字段而不是我分组的字段时,我会得到 [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
4

2 回答 2

3

就是这样COUNT工作的。当您指定列NULL值时,将从计算中消除。并且因为您COUNT设置在与 相同的列上GROUP BY,所以您收到0NULL组 - 您计算的所有值都是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]
于 2013-04-10T22:27:23.240 回答
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
于 2013-04-10T22:48:31.690 回答