概览
在 MySQL 中,COUNT() 函数返回表中行的数量。
COUNT(DISTINCT expression) 返回指定表达式中包含非 NULL 值的行数。
语法
使用 COUNT(DISTINCT) 在 SELECT 语句中:
SELECT
COUNT(DISTINCT expression)
FROM
table_name;
示例
我们有名为 sales 的表。
| item | customer_name |
|---|---|
| book | Alex |
| pen | Bob |
| book | Alex |
| book | Jim |
| shoes | Jim |
| pen | Bob |
| backpack | Bob |
| book | Bob |
| wallet | Alex |
| wallet | Alex |
| book | Bob |
| backpack | Jim |
由于客户可能会进行多次购买,customer_name 字段存在重复值。因此,为了统计不同客户的数量:
SELECT
COUNT(DISTINCT customer_name)
FROM
sales;
结果是 3。
一位顾客可能多次购买同一件商品,为了了解每个顾客已经购买了多少不同的商品,我们可以使用 GROUP BY:
SELECT
customer_name,
COUNT(DISTINCT item) as unique_item
FROM
sales
GROUP BY
customer_name;
结果是:
| customer_name | unique_item |
|---|---|
| Alex | 2 |
| Bob | 3 |
| Jim | 3 |
我们还可以添加 WHERE 子句,来统计购买该 book 产品的唯一客户数量。
SELECT
COUNT(DISTINCT customer_name) book_customers
FROM
sales
WHERE
item = 'book';
结果是 3。
在寻找好用的数据库图形工具?TablePlus 是一款原生客户端,提供直观且功能丰富的图形界面,可同时访问和管理 Oracle、MySQL、SQL Server、PostgreSQL 等数据库。
不在 Mac 上? 下载 TablePlus for Windows.
使用 Linux? 下载适用于 Linux 的 TablePlus
需要在外出时快速编辑数据? 下载适用于 iOS 的 TablePlus
