將大於和小於特定數字的計數值計算並顯示在單獨的 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP