PostgreSQL HAVING 子句

HAVING

HAVING 子句已添加到 SQL 中,因为 WHERE 子句不能与聚合函数一起使用。

聚合函数通常与 GROUP BY 子句一起使用,通过添加 HAVING,我们可以像使用 WHERE 子句一样编写条件。

实例

仅列出代表人数超过 5 次的国家:

  1. SELECT COUNT(customer_id), country
  2. FROM customers
  3. GROUP BY country
  4. HAVING COUNT(customer_id) > 5;

更多 HAVING 实例

以下 SQL 语句仅列出总价为 400 美元或以上的订单:

实例
  1. SELECT order_details.order_id, SUM(products.price)
  2. FROM order_details
  3. LEFT JOIN products ON order_details.product_id = products.product_id
  4. GROUP BY order_id
  5. HAVING SUM(products.price) > 400.00;

列出已订购 1000 美元或以上的客户:

实例
  1. SELECT customers.customer_name, SUM(products.price)
  2. FROM order_details
  3. LEFT JOIN products ON order_details.product_id = products.product_id
  4. LEFT JOIN orders ON order_details.order_id = orders.order_id
  5. LEFT JOIN customers ON orders.customer_id = customers.customer_id
  6. GROUP BY customer_name
  7. HAVING SUM(products.price) > 1000.00;