Sql-Server

為什麼 COUNT() 聚合為 ‘NULL’ 返回 0?

  • November 27, 2020

一個 SELECT 語句返回幾行:

SELECT
 ColA
FROM
 TableA
WHERE
 ColA IS NULL

我在 TableA 中得到 47 行 ColA 為“NULL”。

ColA
NULL
NULL
NULL
etc...

如果我向此查詢添加聚合:

SELECT
 ColA,
 COUNT(ColA) AS theCount
FROM
 TableA
WHERE
 ColA IS NULL
GROUP BY ColA

我明白了

ColA | theCount
NULL | 0

為什麼會發生這種情況,我該怎麼做才能避免這種情況?

聚合函式忽略空值。

所以

SELECT COUNT(cola) AS thecount
FROM tablea

相當於

SELECT count(*) AS thecount
FROM tablea
WHERE cola IS NOT NULL;

由於您的所有值都為空,count(cola)因此必須返回零。

如果要計算為空的行,則需要count(*)

SELECT cola,
      count(*) AS theCount
FROM tablea
WHERE cola is null
GROUP BY cola;

或更簡單:

SELECT count(*) AS theCount
FROM tablea
WHERE cola is null;

如果要在單個查詢中計算 NULL和NOT NULL 值,請使用:

SELECT count(cola) as not_null_count, 
      count(case when cola is null then 1 end) as null_count
FROM tablea;

引用自:https://dba.stackexchange.com/questions/153586