如何计算 MySQL 表中非空或非零列的数目?
为此,请使用 if() 方法。让我们先创建一个表 -
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Number1 int, -> Number2 int -> ); Query OK, 0 rows affected (1.15 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable(Number1,Number2) values(10,20); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable(Number1,Number2) values(0,32); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable(Number1,Number2) values(40,0); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(Number1,Number2) values(40,50); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
这将生成以下输出 -
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 10 | 20 | | 2 | 0 | 32 | | 3 | 40 | 0 | | 4 | 40 | 50 | +----+---------+---------+ 4 rows in set (0.00 sec)
以下查询可计算表中非空或非零列的数目 -
mysql> select *, -> if(Number1 <> 0,1,0)+if(Number2 <> 0,1,0) AS TotalCount -> from DemoTable;
输出
这将生成以下输出 -
+----+---------+---------+------------+ | Id | Number1 | Number2 | TotalCount | +----+---------+---------+------------+ | 1 | 10 | 20 | 2 | | 2 | 0 | 32 | 1 | | 3 | 40 | 0 | 1 | | 4 | 40 | 50 | 2 | +----+---------+---------+------------+ 4 rows in set (0.00 sec)
广告