📅  最后修改于: 2023-12-03 15:20:14.414000             🧑  作者: Mango
在 SQL 查询中,HAVING
子句用于过滤聚合函数的结果。HAVING
子句可以基于聚合函数的返回结果来进行过滤,只返回满足指定条件的记录。
HAVING
子句的基本语法如下所示:
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING condition
ORDER BY column(s);
在 HAVING
子句中,可以使用以下运算符:
运算符 | 描述 --- | --- = | 等于 <> | 不等于
| 大于 < | 小于 = | 大于等于 <= | 小于等于 BETWEEN | 在指定范围内 LIKE | 模糊匹配 IN | 是否包含于一个列表中
示例数据为一个 Orders
表,其中包含 OrderID
, CustomerID
, OrderDate
和 TotalAmount
等字段信息。
OrderID | CustomerID | OrderDate | TotalAmount
1 | C001 | 2021-01-01 | 100.00
2 | C002 | 2021-01-02 | 200.00
3 | C001 | 2021-01-03 | 150.00
4 | C003 | 2021-01-04 | 120.00
5 | C002 | 2021-01-05 | 300.00
SELECT CustomerID, SUM(TotalAmount) as Total
FROM Orders
GROUP BY CustomerID
HAVING SUM(TotalAmount) > 200;
结果如下所示:
CustomerID | Total
C002 | 500
因为只有 C002 的订单的总金额大于 200,所以只返回了 C002 的记录。
SELECT CustomerID, SUM(TotalAmount) as Total
FROM Orders
GROUP BY CustomerID
HAVING SUM(TotalAmount) BETWEEN 100 AND 200;
结果如下所示:
CustomerID | Total
C001 | 250
C003 | 120
因为只有 C001 和 C003 的订单的总金额在 100 到 200 之间,所以返回了这两个客户的记录。
SELECT CustomerID, SUM(TotalAmount) as Total
FROM Orders
GROUP BY CustomerID
HAVING SUM(TotalAmount) <= 150 AND CustomerID = 'C001';
结果如下所示:
CustomerID | Total
C001 | 100
因为只有 C001 的订单的总金额小于等于 150 是否定和 C001 客户 ID 同时满足,所以只返回了 C001 的记录。
HAVING
子句是在分组的数据上进行过滤,可以与 GROUP BY
子句一起使用,用于处理聚合函数查询的过滤条件。常见的使用场景是在查询结果中找到满足特定条件的记录。