'case column' in HAVING clause

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Philia
    New Member
    • Dec 2007
    • 5

    'case column' in HAVING clause

    Hello,

    I'm having problem migrating to postgreSQL from MySQL, some of my queries does not work in postgres.

    Query(simplifie d):
    Code:
    SELECT t1.bus_stop, t1.time,
    (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column
    FROM routes AS t1
    GROUP BY  t1.bus_stop, t1.time
    HAVING sort_column > 2200 ORDER BY sort_column  LIMIT 1
    Error:
    Code:
    ERROR:  column "sort_column" does not exist
    How to use a 'case column' in HAVING clause?
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    Maybe like this

    Code:
    SELECT i,j, sort_kolumn from (
    SELECT t1.bus_stop as i, t1.time as j,
    (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column FROM routes AS t1) foo
    GROUP BY  i,j
    HAVING sort_column > 2200 ORDER BY sort_column  LIMIT 1
    Does it work?

    Comment

    • Philia
      New Member
      • Dec 2007
      • 5

      #3
      Originally posted by rski
      Maybe like this

      Code:
      SELECT i,j, sort_kolumn from (
      SELECT t1.bus_stop as i, t1.time as j,
      (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column FROM routes AS t1) foo
      GROUP BY  i,j
      HAVING sort_column > 2200 ORDER BY sort_column  LIMIT 1
      Does it work?
      Yes, it works. Thank you rski. :)
      But for me it looks like way around the problem, is there a better way to do this?
      I'm migrating to postgres to speed up my aplication so I'm concerned about the speed of this query.

      Comment

      • rski
        Recognized Expert Contributor
        • Dec 2006
        • 700

        #4
        If i'm right HAVING clause can't have CASE clause.
        Say what do you want to achieve and what is table structure, maybe there is another solution than yours.

        Comment

        Working...