SQL COUNT(*) 包括空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40679208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:00:13  来源:igfitidea点击:

COUNT(*) Includes Null Values?

sqlsql-server

提问by Derrick Moeller

MSDNdocumentation states:

MSDN文档指出:

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.

COUNT(*) 返回组中的项目数。这包括 NULL 值和重复项。

How can you have a null value in a group? Can anyone explain the point they're trying to make?

你怎么能在一个组中有一个空值?任何人都可以解释他们试图提出的观点吗?

回答by Juan Carlos Oropeza

If you have this table

如果你有这张桌子

Table1:

表格1:

 Field1    Field2    Field3
 ---------------------------
   1         1         1
  NULL      NULL      NULL
   2         2        NULL
   1         3         1

Then

然后

 SELECT COUNT(*), COUNT(Field1), COUNT(Field2), COUNT(DISTINCT Field3)
 FROM Table1

Output Is:

输出是:

 COUNT(*) = 4; -- count all rows, even null/duplicates

 -- count only rows without null values on that field
 COUNT(Field1) = COUNT(Field2) = 3

 COUNT(Field3) = 2 
 COUNT(DISTINCT Field3) = 1 -- Ignore duplicates

回答by ACon

You can have a Null value in a row depending on how you do your joins. Be sure you are counting the right field or correcting your joins.

根据您的连接方式,您可以在一行中有一个 Null 值。确保您正在计算正确的字段或更正您的连接。