Subselect on array_agg in postgresql

霸气de小男生 提交于 2019-12-11 03:47:11

问题


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:


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.



来源:https://stackoverflow.com/questions/16821764/subselect-on-array-agg-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!