SQL HAVING 语句

HAVING 语句

在 SQL 中增加 HAVING 语句原因是,WHERE 关键字无法与合计函数(如 SUM,Count 等)一起使用。

HAVING 语句能代替 WHERE 成为合计函数的条件语句。

SQL HAVING 语法
  1. SELECT column_name, aggregate_function(column_name)
  2. FROM table_name
  3. WHERE column_name operator value
  4. GROUP BY column_name
  5. HAVING aggregate_function(column_name) operator value

SQL HAVING 实例

我们拥有下面这个 "Orders" 表:

O_IdOrderDateOrderPriceCustomer
12021/12/291000Bush
22021/11/231600Carter
32021/10/05700Bush
42021/09/28300Bush
52021/08/062000Adams
62021/07/21100Carter

现在,我们希望查找订单总金额少于 2000 的客户。

我们使用如下 SQL 语句:

  1. SELECT Customer,SUM(OrderPrice) FROM Orders
  2. GROUP BY Customer
  3. HAVING SUM(OrderPrice)<2000

结果集类似:

CustomerSUM(OrderPrice)
Carter1700

现在我们希望查找客户 "Bush" 或 "Adams" 拥有超过 1500 的订单总金额。

我们在 SQL 语句中增加了一个普通的 WHERE 子句:

  1. SELECT Customer,SUM(OrderPrice) FROM Orders
  2. WHERE Customer='Bush' OR Customer='Adams'
  3. GROUP BY Customer
  4. HAVING SUM(OrderPrice)>1500

结果集:

CustomerSUM(OrderPrice)
Bush2000
Adams2000