使用 MySQL 統計列表中特定專案的不同數量


要查詢特定專案的不同數量,請使用 COUNT() 以及 GROUP BY 子句。讓我們首先建立一個表 −

mysql> create table DemoTable1854
     (
     Name varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable1854 values('John-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('Chris-Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('Adam-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('John-Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('John-Smith');
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select * from DemoTable1854;

這將產生以下輸出 −

+-------------+
| Name        |
+-------------+
| John-Smith  |
| Chris-Brown |
| Adam-Smith  |
| John-Doe    |
| John-Smith  |
+-------------+
5 rows in set (0.00 sec)

以下是獲取列表中特定專案不同數量的查詢 −

mysql> select Name,count(Name) from DemoTable1854
     where Name like 'John-%'
     group by Name;

這將產生以下輸出 −

+------------+-------------+
| Name       | count(Name) |
+------------+-------------+
| John-Smith |           2 |
| John-Doe   |           1 |
+------------+-------------+
2 rows in set (0.00 sec)

更新日期:2019-12-26

153 次瀏覽

kickstart 您職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.