如何在 MySQL 中返回非重複值及其計數?
若要僅返回非重複值,請使用 GROUP BY 子句。
我們首先建立一個表 −
mysql> create table DemoTable754 (ProductPrice int); Query OK, 0 rows affected (0.48 sec)
使用插入命令在表中插入一些記錄 −
mysql> insert into DemoTable754 values(200); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable754 values(500); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable754 values(200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable754 values(500); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable754 values(800); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable754 values(900); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable754 values(200); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable754 values(200); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable754 values(900); Query OK, 1 row affected (0.11 sec)
使用 select 語句在表中顯示所有記錄 −
mysql> select *from DemoTable754;
這將產生以下輸出 -
+--------------+ | ProductPrice | +--------------+ | 200 | | 500 | | 200 | | 500 | | 800 | | 900 | | 200 | | 200 | | 900 | +--------------+ 9 rows in set (0.00 sec)
以下是返回非重複值及其計數的查詢 −
mysql> select ProductPrice,count(ProductPrice) from DemoTable754 group by ProductPrice;
這將產生以下輸出 -
+--------------+---------------------+ | ProductPrice | count(ProductPrice) | +--------------+---------------------+ | 200 | 4 | | 500 | 2 | | 800 | 1 | | 900 | 2 | +--------------+---------------------+ 4 rows in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP