使用 MySQL 計數多行並在不同列(和單行)中顯示結果
我們首先建立一個表 −
mysql> create table DemoTable1452 -> ( -> FavouriteColor varchar(50) -> ); Query OK, 0 rows affected (2.42 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable1452 values('Red');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1452 values('Blue');
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable1452 values('Blue');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable1452 values('Red');
Query OK, 1 row affected (0.29 sec)使用 select 語句從表中顯示所有記錄 −
mysql> select * from DemoTable1452;
這會產生以下輸出 −
+----------------+ | FavouriteColor | +----------------+ | Red | | Yellow | | Yellow | | Yellow | | Blue | | Blue | | Red | +----------------+ 7 rows in set (0.00 sec)
以下是計數多行並在不同列中顯示結果的查詢 −
mysql> select sum(FavouriteColor='Red') as NumberOfRedColor, -> sum(FavouriteColor='Yellow') as NumberOfYellowColor, -> sum(FavouriteColor='Blue') as NumberOfBlueColor -> from DemoTable1452;
這會產生以下輸出 −
+------------------+---------------------+-------------------+ | NumberOfRedColor | NumberOfYellowColor | NumberOfBlueColor | +------------------+---------------------+-------------------+ | 2 | 3 | 2 | +------------------+---------------------+-------------------+ 1 row in set (0.27 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP