文档

HAVING

更新时间:

HAVING子句与聚合函数以及GROUP BY子句一起使用,在分组和聚合计算完成后,HAVING子句对分组进行过滤,去掉不满足条件的分组。

[ HAVING condition ]     

注意事项

  • HAVING条件中引用的列必须为分组列或引用了聚合函数结果的列。

  • HAVING子句必须与聚合函数以及GROUP BY子句一起使用,用于对GROUP BY分组进行过滤,去掉不满足条件的分组。

示例

在CUSTOMER表中,进行分组查询,查询账户余额大于指定值的记录。

SELECT count(*), mktsegment, nationkey,
       CAST(sum(acctbal) AS bigint) AS totalbal
FROM customer
GROUP BY mktsegment, nationkey
HAVING sum(acctbal) > 5700000
ORDER BY totalbal DESC;

 _col0 | mktsegment | nationkey | totalbal
-------+------------+-----------+----------
  1272 | AUTOMOBILE |        19 |  5856939
  1253 | FURNITURE  |        14 |  5794887
  1248 | FURNITURE  |         9 |  5784628
  1243 | FURNITURE  |        12 |  5757371
  1231 | HOUSEHOLD  |         3 |  5753216
  1251 | MACHINERY  |         2 |  5719140
  1247 | FURNITURE  |         8 |  5701952