HAVING
子句用于过滤GROUP BY
分组聚合后的数据。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
文档内容是否对您有帮助?