【发布时间】:2015-02-05 18:23:24
【问题描述】:
使用 Postgres 9.3...
有人能解释一下为什么我不能直接在未嵌套的数组上使用 max 函数吗?
据我了解,unnest 函数返回一个“setof”,就像 select 语句一样。那么为什么这个查询的简短版本不起作用呢? (我是在概念上遗漏了什么,还是我的问题与语法相关?)
table: foo_history:
id | history::smallint
-----------------------------------
1 | {10,20,30,50,40}
这不起作用?
Select id, max(unnest(history)) as vMax from foo_history;
...但是这个可以...?
WITH foo as (
select id, unnest(history) as history
from foo_history
)
Select
id, max(history) as vMax
From foo
Group by id;
【问题讨论】:
-
尽管我编写了自己的函数来解决问题,但我还是有点困惑。 'unnest' 函数返回一组行,而 max 函数对一组行进行操作。是有错误还是我没有得到什么?
-
是的,有。
max是一个聚合,因此它对每个元组的一个输入进行操作。它不能将集合作为这样的输入。要按照您描述的方式表达它,您可以使用子查询,例如select id, (select max(x) from unnest(history) x) as vmax from foo_history。
标签: arrays postgresql max postgresql-9.3