Connecting Tech Pros Worldwide Help | Site Map

'case column' in HAVING clause

Newbie
 
Join Date: Dec 2007
Posts: 5
#1: Apr 3 '08
Hello,

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

Query(simplified):
Expand|Select|Wrap|Line Numbers
  1. SELECT t1.bus_stop, t1.time,
  2. (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column
  3. FROM routes AS t1
  4. GROUP BY  t1.bus_stop, t1.time
  5. HAVING sort_column > 2200 ORDER BY sort_column  LIMIT 1
Error:
Expand|Select|Wrap|Line Numbers
  1. ERROR:  column "sort_column" does not exist
How to use a 'case column' in HAVING clause?
Moderator
 
Join Date: Dec 2006
Location: Europe
Posts: 292
#2: Apr 3 '08

re: 'case column' in HAVING clause


Maybe like this

Expand|Select|Wrap|Line Numbers
  1. SELECT i,j, sort_kolumn from (
  2. SELECT t1.bus_stop as i, t1.time as j,
  3. (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column FROM routes AS t1) foo
  4. GROUP BY  i,j
  5. HAVING sort_column > 2200 ORDER BY sort_column  LIMIT 1
Does it work?
Newbie
 
Join Date: Dec 2007
Posts: 5
#3: Apr 3 '08

re: 'case column' in HAVING clause


Quote:

Originally Posted by rski

Maybe like this

Expand|Select|Wrap|Line Numbers
  1. SELECT i,j, sort_kolumn from (
  2. SELECT t1.bus_stop as i, t1.time as j,
  3. (case when t1.time >2200 then t1.time + 10000 else t1.time END) AS sort_column FROM routes AS t1) foo
  4. GROUP BY  i,j
  5. 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.
Moderator
 
Join Date: Dec 2006
Location: Europe
Posts: 292
#4: Apr 3 '08

re: 'case column' in HAVING clause


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.
Reply