MySQL 如何选择统计等于 0 和大于 0 的值,且这些值来自同一列?
为此,请使用 CASE 语句。我们先创建一个表 −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(50); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+--------+ | Number | +--------+ | 10 | | 0 | | 20 | | 50 | | 0 | | 0 | | 40 | +--------+ 7 rows in set (0.00 sec)
现在,我们来看看如何选择统计等于 0 和大于 0 的值,且这些值来自同一列
mysql> select sum(case when Number > 0 then 1 else 0 end ) AS TotalValueWhichIsGreaterThanZero, sum(case when Number = 0 then 1 else 0 end) AS TotalValueWhichIsEqualToZero from DemoTable where Number >=0;
输出
+----------------------------------+------------------------------+ | TotalValueWhichIsGreaterThanZero | TotalValueWhichIsEqualToZero | +----------------------------------+------------------------------+ | 4 | 3 | +----------------------------------+------------------------------+ 1 row in set (0.00 sec)
广告