3

Is there a way to use a value from an aggregate function in a having clause in Postgresql 9.2+?

For example, I would like to get each monkey_id with a 2nd highest number > 123, as well as the second highest number. In the example below, I'd like to get (monkey_id 1, number 222).

monkey_id | number
------------------
1         | 222
1         | 333
2         | 0
2         | 444

SELECT 
  monkey_id, 
  (array_agg(number ORDER BY number desc))[2] as second 
FROM monkey_numbers 
GROUP BY monkey_id
HAVING second > 123

I get column "second" does not exist.

1 Answer 1

4

You will have to place that in the having clause

SELECT 
  monkey_id
FROM monkey_numbers 
GROUP BY monkey_id
HAVING array_agg(number ORDER BY number desc)[2] > 123

The explanation is that the having will be executed before the select so second still doesn't exist at that time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.