Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subselect on array_agg in postgresql

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.

like image 692
tee Avatar asked Apr 27 '26 17:04

tee


1 Answers

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.

like image 51
Clodoaldo Neto Avatar answered Apr 30 '26 07:04

Clodoaldo Neto