SQL 即使有 NULL 值,计数 NULL 值也是 0
SQL Count NULL values is 0 even when there are NULL values
在特定情况下,我有一个数据库 table,其中填充了 1070 个项目,在这个过程中的某个时刻,我向其中添加了一个名为 'Current_Status' 的列。因此,所有项目都有一个初始为 NULL.
的新字段
此table用作队列,对于处理的每一行,我将'Current_Status'字段更新为'Processed'或'Non processed'。
为了查看流程进行得如何,我使用以下查询计算了状态仍为 NULL 的剩余项目:
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
问题是,在前 1000 个项目之后,该查询执行的结果是 0
,即使我检查并使用 SELECT * FROM Table_Name
查询显示仍然有一些行具有状态NULL.
知道是什么原因造成的吗?
我使用 Azure Data Studio 1.4.5 检查了这种情况。
这是因为您为计数提供的列值为 null
。相反,使用 count(*)
:
SELECT COUNT(*) FROM Table_Name WHERE [Current_Status] IS NULL
示例数据:
current_status
--------------
Processed
Null
Not Processed
Null
以及两个查询的区别:
count(current_status)
SELECT count(current_status) FROM table_name WHERE current_status IS NULL
0
计数(*)
SELECT count(*) FROM table_name WHERE current_status IS NULL
2
有
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
你说"take all rows where the current_status
is null and count how many of these current_status
are not null"。这当然是零。 COUNT(<expression>)
计算表达式的非空出现次数。
您想改为计算行数:
SELECT COUNT(*) FROM table_name WHERE current_status IS NULL;
或剩余计数:
SELECT COUNT(*) - COUNT(current_status) FROM table_name;
在特定情况下,我有一个数据库 table,其中填充了 1070 个项目,在这个过程中的某个时刻,我向其中添加了一个名为 'Current_Status' 的列。因此,所有项目都有一个初始为 NULL.
的新字段此table用作队列,对于处理的每一行,我将'Current_Status'字段更新为'Processed'或'Non processed'。
为了查看流程进行得如何,我使用以下查询计算了状态仍为 NULL 的剩余项目:
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
问题是,在前 1000 个项目之后,该查询执行的结果是 0
,即使我检查并使用 SELECT * FROM Table_Name
查询显示仍然有一些行具有状态NULL.
知道是什么原因造成的吗?
我使用 Azure Data Studio 1.4.5 检查了这种情况。
这是因为您为计数提供的列值为 null
。相反,使用 count(*)
:
SELECT COUNT(*) FROM Table_Name WHERE [Current_Status] IS NULL
示例数据:
current_status
--------------
Processed
Null
Not Processed
Null
以及两个查询的区别:
count(current_status)
SELECT count(current_status) FROM table_name WHERE current_status IS NULL
0
计数(*)
SELECT count(*) FROM table_name WHERE current_status IS NULL
2
有
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
你说"take all rows where the current_status
is null and count how many of these current_status
are not null"。这当然是零。 COUNT(<expression>)
计算表达式的非空出现次数。
您想改为计算行数:
SELECT COUNT(*) FROM table_name WHERE current_status IS NULL;
或剩余计数:
SELECT COUNT(*) - COUNT(current_status) FROM table_name;