📅  最后修改于: 2023-12-03 15:33:44.746000             🧑  作者: Mango
在 PostgreSQL 中,HAVING 子句用于筛选 GROUP BY 子句生成的结果,使得只有满足特定条件的分组才被返回。HAVING 子句与 WHERE 子句的区别在于,WHERE 子句筛选的是行,而 HAVING 子句筛选的是分组。
HAVING 子句的基本语法如下:
SELECT
column1,
column2,
...
FROM
table_name
WHERE
condition
GROUP BY
column1,
column2,
...
HAVING
condition
在以上语法中,condition
是筛选条件,可以使用聚合函数。在选择列列出的列名前使用聚合函数时,此列也将成为分组列,即 GROUP BY
的一部分。
假如我们有以下一张订单表:
| order_id | customer_name | order_date | total_amount | | -------- | ------------- | ---------- | ------------ | | 1 | Alice | 2021-01-01 | 100 | | 2 | Bob | 2021-01-02 | 150 | | 3 | Alice | 2021-01-03 | 200 | | 4 | Bob | 2021-01-04 | 50 |
要查询每个客户的总订单金额,可以使用以下 SQL 语句:
SELECT
customer_name,
sum(total_amount) as total_order_amount
FROM
orders
GROUP BY
customer_name
该查询将生成以下结果:
| customer_name | total_order_amount | | ------------- | ----------------- | | Alice | 300 | | Bob | 200 |
现在,假如我们只想查询订单总金额大于等于 200 的客户,使用 HAVING
子句可以轻松实现:
SELECT
customer_name,
sum(total_amount) as total_order_amount
FROM
orders
GROUP BY
customer_name
HAVING
sum(total_amount) >= 200
该查询将只生成以下结果:
| customer_name | total_order_amount | | ------------- | ----------------- | | Alice | 300 |