在count中只包含一次NULL

时间:2017-10-10 06:26:25

标签: mysql sql

如何在整体计数中包含NULL?

例如在下面的查询中,我希望计数为2而不是仅1('abc'和NULL)

mysql> create table test.todel (name varchar(100));

mysql> insert into test.todel values ('abc');

mysql> insert into test.todel values ('abc');

mysql> insert into test.todel values (null);

mysql> select count(distinct(name)) from test.todel;
+-----------------------+
| count(distinct(name)) |
+-----------------------+
|                     1 |
+-----------------------+
1 row in set (0.00 sec)

更新

答案的问题是,即使所有值都为NULL,它也会返回1。

drop table test.todel;

create table test.todel (name varchar(100));

insert into test.todel values (null);

insert into test.todel values (null);

insert into test.todel values (null);

在这种情况下,我需要返回0,如果有任何非空值,那么如果存在null,则计数应该是非空的+ 1。

4 个答案:

答案 0 :(得分:2)

将其替换为其他值。

select count(distinct(coalesce(name, 1))) from test.todel;

COALESCE()函数返回其第一个不为NULL的参数。

更新问题后编辑:

你可以这样做:

SELECT COUNT(*) FROM (SELECT DISTINCT name FROM test.todel) subquery_alias

答案 1 :(得分:1)

如果您计算具有null值的行,那么您可以这样:

select count(distinct(ifnull(name, 1))) from test.todel;

由于count功能不计算null

答案 2 :(得分:1)

您可以使用null coalesce函数,该函数将获取第一个参数的值,该参数不是null:

SELECT COUNT(DISTINCT(COALESCE(name, 1))) FROM test.todel;

答案 3 :(得分:0)

您可以使用其他方式计算:

SELECT count(distinct(*)) FROM test.todel WHERE name IN (....)

当然WHERE IN不是很快,所以你可能会考虑HAVING或类似的。

相关问题