如何計算 MySQL 中的列的獨特值?


你需要使用 GROUP BY 實現此目的。我們先建立一個表 −

mysql> create table DemoTable
   (
   StudentFirstName varchar(20)
   );
Query OK, 0 rows affected (0.74 sec)

使用 insert 命令向表插入記錄 −

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (1.34 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select * from DemoTable;

將產生以下輸出 −

+------------------+
| StudentFirstName |
+------------------+
| John             |
| Carol            |
| John             |
| John             |
| Bob              |
| David            |
| Bob              |
| Carol            |
| Robert           |
+------------------+
9 rows in set (0.00 sec)

以下是統計 MySQL 中列的唯一值的查詢 −

mysql> select StudentFirstName,count(*) from DemoTable
group by StudentFirstName;

將產生以下輸出 −

+------------------+----------+
| StudentFirstName | count(*) |
+------------------+----------+
| John             | 3        |
| Carol            | 2        |
| Bob              | 2        |
| David            | 1        |
| Robert           | 1        |
+------------------+----------+
5 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

159 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.