【问题标题】:Referring to a select aggregate column alias in the having clause in Postgres在 Postgres 的 have 子句中引用选择聚合列别名
【发布时间】:2015-09-23 03:05:04
【问题描述】:

我正在从 MySQL 迁移到 Postgres。在 MySQL 中我可以使用

select sum(clicks) c from table where event_date >= '1999-01-01' 
group by keyword_id 
having c > 10

Postgres 报错

错误:“c”列不存在

在 Postgres 中,我必须在 have 子句中重复该功能

select sum(clicks) c from table where event_date >= '1999-01-01' 
group by keyword_id 
having sum(clicks) > 10

代码中有很多地方需要更改。 Postgres 中是否有允许它在 having 子句中使用列别名的设置?

【问题讨论】:

    标签: mysql sql postgresql


    【解决方案1】:

    Postgres 中是否有允许它在 having 子句中使用列别名的设置?

    没有。允许引用HAVING 中的SELECT-list 条目的实现超出了标准。

    您应该使用子查询,例如

    select
      c
    from (
      select 
        sum(clicks) c
      from table
      where event_date >= '1999-01-01'
      group by keyword_id 
    ) x
    where c > 10;
    

    ...或重复聚合。

    【讨论】:

      【解决方案2】:

      您可以使用WITH Queries (Common Table Expressions) 来实现如下结果

      WITH t
      AS (
          SELECT sum(clicks) c
          FROM TABLE
          WHERE event_date >= '1999-01-01'
          GROUP BY keyword_id
          )
      SELECT c
      FROM t
      WHERE c > 10
      

      【讨论】:

      • 聪明,但我还是得到处改代码。
      • @Chloe 我刚刚回答是为了让您知道您的问题的另一种方式
      • 这在某种程度上比子查询更好吗?非标准将是这种方法的缺点之一。
      猜你喜欢
      • 2010-12-19
      • 2013-06-08
      • 2012-01-12
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多