有没有办法在Postgresql 9.2 +中的having子句中使用聚合函数的值?
例如,我希望每个monkey_id
获得第二高number
> 123,以及第二高的数字。在下面的例子中,我想得到(monkey_id 1,数字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
我得到column "second" does not exist
。
答案 0 :(得分:3)
您必须将其放在having子句
中SELECT
monkey_id
FROM monkey_numbers
GROUP BY monkey_id
HAVING array_agg(number ORDER BY number desc)[2] > 123
解释是having
将在select
之前执行,因此second
当时仍然不存在。