如何使用单个 MySQL 查询来计算忽略空值的列值?
为此,可以使用 COUNT() 方法,该方法不包括 NULL 值。我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Name varchar(100), -> CountryName varchar(100) -> ); Query OK, 0 rows affected (0.49 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('John',null); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Chris','US'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Robert',null); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Bob','UK'); Query OK, 1 row affected (0.57 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
输出
这将产生以下输出 -
+--------+-------------+ | Name | CountryName | +--------+-------------+ | John | NULL | | Chris | US | | Robert | NULL | | Bob | UK | +--------+-------------+ 4 rows in set (0.00 sec)
以下是使用 COUNT() 并忽略 NULL 的查询 -
mysql> select count(Name) AS TotalName,count(CountryName) AS CountryWhichIsNotNull from DemoTable;
输出
这将产生以下输出 -
+-----------+-----------------------+ | TotalName | CountryWhichIsNotNull | +-----------+-----------------------+ | 4 | 2 | +-----------+-----------------------+ 1 row in set (0.00 sec)
广告