用单个MySQL查询计算零、NULL和除零和NULL之外的不同值的数量

用单个MySQL查询计算零、NULL和除零和NULL之外的不同值的数量

首先创建一个表 –

mysql> create table DemoTable(
   Value int
);
Query OK, 0 rows affected (1.35 sec)

使用插入命令向表中插入一些记录 –

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)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

MySQL 教程