HAVING 子句 - Amazon Redshift

HAVING 子句

HAVING 子句将条件应用于查询返回的中间分组结果集。

语法

[ HAVING condition ]

例如,您可以限制 SUM 函数的结果:

having sum(pricepaid) >10000

在应用所有 WHERE 子句条件并完成 GROUP BY 操作后,应用 HAVING 条件。

条件本身采用与任何 WHERE 子句条件相同的形式。

使用说明

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

  • 在 HAVING 子句中,无法指定:

    • 引用选择列表项的序号。仅 GROUP BY 和 ORDER BY 子句接受序号。

示例

以下查询按名称计算所有活动的门票总销售额,然后消除总销售额小于 $800000 的活动。HAVING 条件应用于选择列表中聚合函数的结果:sum(pricepaid)

select eventname, sum(pricepaid) from sales join event on sales.eventid = event.eventid group by 1 having sum(pricepaid) > 800000 order by 2 desc, 1; eventname | sum -----------------+----------- Mamma Mia! | 1135454.00 Spring Awakening | 972855.00 The Country Girl | 910563.00 Macbeth | 862580.00 Jersey Boys | 811877.00 Legally Blonde | 804583.00

以下查询计算类似的结果集。不过,在本示例中,HAVING 条件将应用于未在选择列表中指定的聚合:sum(qtysold)。将从最终结果中消除未售出 2000 张以上的门票的活动。

select eventname, sum(pricepaid) from sales join event on sales.eventid = event.eventid group by 1 having sum(qtysold) >2000 order by 2 desc, 1; eventname | sum -----------------+----------- Mamma Mia! | 1135454.00 Spring Awakening | 972855.00 The Country Girl | 910563.00 Macbeth | 862580.00 Jersey Boys | 811877.00 Legally Blonde | 804583.00 Chicago | 790993.00 Spamalot | 714307.00

以下查询按名称计算所有活动的门票总销售额,然后消除总销售额小于 $800000 的活动。HAVING 条件应用于选择列表中聚合函数的结果(对 sum(pricepaid) 使用别名 pp)。

select eventname, sum(pricepaid) as pp from sales join event on sales.eventid = event.eventid group by 1 having pp > 800000 order by 2 desc, 1; eventname | pp -----------------+----------- Mamma Mia! | 1135454.00 Spring Awakening | 972855.00 The Country Girl | 910563.00 Macbeth | 862580.00 Jersey Boys | 811877.00 Legally Blonde | 804583.00