如果我们需要根据聚合函数(例如 MIN() 和 MAX()、SUM() 和 AVG() 以及 COUNT())筛选结果集,则使用 SQL `HAVING` 子句。
示例
-- select customers with the same first name based on their age count
SELECT COUNT(age) AS Count, first_name
FROM Customers
GROUP BY first_name
HAVING COUNT(age) > 1;
这里,SQL 命令
- 计算每行的 `age` 并按 `first_name` 分组
- 如果 `age` 的计数大于 **1**,则返回结果集(从而筛选出具有相同 `first_name` 的客户)
SQL HAVING 语法
SQL `HAVING` 子句的语法是
SELECT AggFunc(column), extra_columns
FROM table
GROUP BY target_column
HAVING condition
这里,
- `AggFunc(column)` 指应用于列的任何聚合函数
- `extra_columns` 是其他需要筛选的额外列
- `GROUP BY` 按 `target_column` 对数据进行分组
- `HAVING condition` 将 `column` 与需要筛选的某些条件进行比较
示例:SQL HAVING
-- select the count of customer ids greater than one and their corresponding country
SELECT COUNT(customer_id), country
FROM Customers
GROUP BY country
HAVING COUNT(customer_id) > 1;
这里,SQL 命令
- 按 country 分组计算行数
- 如果它们的**计数**大于 **1**,则返回结果集。

注意:引入 `HAVING` 子句是因为 `WHERE` 子句不支持聚合函数。此外,`GROUP BY` 必须在 `HAVING` 子句之前使用。要了解更多信息,请访问 SQL GROUP BY。
SQL HAVING 与 WHERE
HAVING 子句 | WHERE 子句 |
---|---|
`HAVING` 子句检查**一组行**的条件。 | `WHERE` 子句检查**每行**的条件。 |
`HAVING` 与聚合函数一起使用。 | `WHERE` 子句不能与聚合函数一起使用。 |
`HAVING` 子句在 `GROUP BY` 子句之后执行。 | `WHERE` 子句在 `GROUP BY` 子句之前执行。 |
让我们看一个例子:
我们可以编写一个 `WHERE` 子句来筛选出 `Orders` 表中 amount 值小于 **500** 的行
SELECT customer_id, amount
FROM Orders
WHERE amount < 500;
但是使用 `HAVING` 子句,我们可以使用聚合函数(如 `SUM`)来计算订单表中的金额总和,并获取每个客户总订单值小于 **500** 的记录
SELECT customer_id, SUM(amount) AS total
FROM Orders
GROUP BY customer_id
HAVING SUM(amount) < 500;