为此,请使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable ( Number int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(10); mysql> insert into DemoTable values(0); mysql> insert into DemoTable values(20); mysql> insert into DemoTable values(50); mysql> insert into DemoTable values(0); mysql> insert into DemoTable values(0); mysql> insert into DemoTable values(40);
使用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)