3

有没有办法在 Postgresql 9.2+ 的 have 子句中使用聚合函数中的值?

例如,我希望每个都monkey_id具有第二高number> 123,以及第二高的数字。在下面的示例中,我想获取 (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

我明白了column "second" does not exist

4

1 回答 1

4

您必须将其放在having子句中

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

解释是,having将在那个时间之前执行,select所以second当时还不存在。

于 2013-05-29T19:01:50.187 回答