如何計算 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 個不同值。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP