如何計算 MySQL 中的不同值?


若要計算不同值,你可以在聚合函式 count() 中使用 distinct。

語法如下 −

select count(distinct yourColumnName) as anyVariableName from yourTableName;

為了理解以上概念,讓我們建立一個表。以下是建立表的查詢 −

mysql> create table DistinctDemo
   −> (
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)

在我們的示例中,讓我們在表中插入重複記錄。插入記錄的查詢如下 −

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

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.17 sec)

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

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.13 sec)

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

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.10 sec)

藉助 select 語句顯示所有記錄。顯示所有記錄的查詢如下 −

mysql> select *from DistinctDemo;

以下是輸出,顯示一些重複記錄 −

+---------+
| Name    |
+---------+
| John    |
| Sam     |
| John    |
| Johnson |
| John    |
| Johnson |
| Sam     |
| Johnson |
+---------+
8 rows in set (0.00 sec)

以下是可以用來計算表中不同值的查詢 −

mysql> select count(distinct Name) as DistinctValues from DistinctDemo;

以下是輸出 −

+----------------+
| DistinctValues |
+----------------+
|              3 |
+----------------+
1 row in set (0.01 sec)

結果 i3 表明我們在表中有 3 個不同值。

更新於: 30-7-2019

8K+ 瀏覽

開啟你的 職業

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.