Referring to a select aggregate column alias in the having clause in Postgres

前端 未结 2 527
名媛妹妹
名媛妹妹 2020-12-11 02:27

I\'m migrating from MySQL to Postgres. In MySQL I can use

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


        
相关标签:
2条回答
  • 2020-12-11 03:14

    Is there a setting in Postgres that will allow it to use column aliases in the having clause?

    No. Implementations that allow references to SELECT-list entries in HAVING are going outside the standard.

    You should use a subquery, e.g.

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

    ... or repeat the aggregate.

    0 讨论(0)
  • 2020-12-11 03:16

    You can use WITH Queries (Common Table Expressions) to achieve the results like below

    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
    
    0 讨论(0)
提交回复
热议问题