如何在 MySQL 中獲取某一列中所有不同值得數量?


讓我們看一個示例,以獲取某一列中所有不同值得數量。首先,我們將建立一個表。

CREATE 命令用於建立表。

mysql> create table DistinctDemo1
   - > (
   - > id int,
   - > name varchar(100)
   - > );
Query OK, 0 rows affected (0.43 sec)

插入記錄

mysql> insert into DistinctDemo1 values(1,'John');
Query OK, 1 row affected (0.34 sec)

mysql> insert into DistinctDemo1 values(2,'John');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DistinctDemo1 values(3,'John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into DistinctDemo1 values(4,'Carol');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DistinctDemo1 values(5,'David');
Query OK, 1 row affected (0.12 sec)

顯示所有記錄

mysql> select *from DistinctDemo1;

以下是顯示所有記錄的輸出。

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | John  |
|    3 | John  |
|    4 | Carol |
|    5 | David |
+------+-------+
5 rows in set (0.00 sec)

以下是獲取數量的語法。

mysql> SELECT name,COUNT(1) as OccurenceValue FROM DistinctDemo1 GROUP BY name ORDER BY OccurenceValue;

以下是輸出。

+-------+----------------+
| name  | OccurenceValue |
+-------+----------------+
| Carol |              1 |
| David |              1 |
| John  |              3 |
+-------+----------------+
3 rows in set (0.04 sec)

更新於: 30-7-2019

4 千+ 瀏覽

開啟您的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.