将大于和小于特定数字的计数值计算并显示在单独的 MySQL 列中?
为此,您可以将 COUNT() 与 CASE 语句结合使用。让我们先创建一个表 -
mysql> create table DemoTable ( Score int ); Query OK, 0 rows affected (0.71 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.77 sec) mysql> insert into DemoTable values(48); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(59); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(33); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(38); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(35); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-------+ | Score | +-------+ | 40 | | 48 | | 59 | | 33 | | 38 | | 89 | | 35 | +-------+ 7 rows in set (0.00 sec)
以下是计算大于和小于特定数字的计数值并将计数值显示在单独的列中的查询 -
mysql> select count( case when Score > 45 then 1 end) as CountOfValueGreaterThan45, count( case when Score <= 45 then 1 end) as CountOfValueLessThanOrEqualTo45 from DemoTable;
这将产生以下输出 -
+---------------------------+---------------------------------+ | CountOfValueGreaterThan45 | CountOfValueLessThanOrEqualTo45 | +---------------------------+---------------------------------+ | 3 | 4 | +---------------------------+---------------------------------+ 1 row in set (0.00 sec)
广告