通过一个 MySQL 查询计算 0、NULL 以及 0 和 NULL 之外的非重复值
我们先创建一个表——
mysql> create table DemoTable( Value int ); Query OK, 0 rows affected (1.35 sec)
使用 insert 命令向表中插入一些记录——
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.59 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.70 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录——
mysql> select *from DemoTable;
这将生成以下输出——
+-------+ | Value | +-------+ | 10 | | NULL | | 10 | | 0 | | 20 | | 10 | | 0 | | NULL | +-------+ 8 rows in set (0.00 sec)
以下是按除 null 和 0 之外的所有值进行分组的查询——
mysql> select sum(Value is null) as NumberOfNull, sum(Value=0) as NumberOfZero, count(distinct Value > 0) as ValueExceptZeroAndNull from DemoTable;
这将生成以下输出——
+--------------+--------------+------------------------+ | NumberOfNull | NumberOfZero | ValueExceptZeroAndNull | +--------------+--------------+------------------------+ | 2 | 2 | 2 | +--------------+--------------+------------------------+ 1 row in set (0.00 sec)
广告