简体   繁体   English

计算 SQL 服务器列中的 NULL 数

[英]Counting the number of NULLs in a SQL Server Column

I have two queries like so:我有两个这样的查询:

SELECT MyId, MyColumn FROM MyTable WHERE MyColumn IS NULL;
SELECT count(MyColumn) as MyCount FROM MyTable WHERE MyColumn IS NULL;

The results I get are:我得到的结果是:

MyId    MyColumn
10      NULL

Why is the count 0 always in the second query?为什么第二个查询中的计数总是 0?

The COUNT() function ignores NULL values, and so the count in your second query will always be zero. COUNT() function 忽略NULL值,因此第二个查询中的计数将始终为零。 Either count something else:要么算点别的:

SELECT COUNT(*) AS MyCount
FROM MyTable
WHERE MyColumn IS NULL;

Or else count over the entire table using a CASE expression to explicitly count NULL values:或者使用CASE表达式计算整个表以显式计算NULL值:

SELECT COUNT(CASE WHEN MyColumn IS NULL THEN 1 END) AS MyCount
FROM MyTable;

Count doesn't count null.计数不计算 null。 You need to do something like this, transform null to 1 then sum them:你需要做这样的事情,将 null 转换为 1,然后将它们相加:

SELECT SUM(CASE WHEN MyColumn IS NULL THEN 1 ELSE 0 END) AS count_nulls
FROM MyTable;

You can simply use count(1) rather than column name in the count function as it ignores null value which counting.您可以简单地在计数 function 中使用 count(1) 而不是列名,因为它忽略了计数的 null 值。

SELECT COUNT(1) AS MyCount
FROM MyTable
WHERE MyColumn IS NULL;

As noted, COUNT(SomeValue) just counts the number of non-nulls, so you actually needed COUNT(*) .如前所述, COUNT(SomeValue)仅计算非空值的数量,因此您实际上需要COUNT(*)

But another way is to subtract the non-nulls from the total但另一种方法是从总数中减去非空值

SELECT COUNT(*) - COUNT(MyColumn) AS MyCount
FROM MyTable;

A WHERE is probably faster though, especially if you have an index on that column.不过, WHERE可能更快,特别是如果您对该列有索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM