Postgres:在int数组中查找最大值?

use*_*963 3 arrays postgresql max postgresql-9.3

使用Postgres 9.3 ...

有人可以解释为什么我不能直接在unnested阵列上使用max函数..?

据我所知,不需要的函数返回一个"setof"就像select语句一样.那么为什么这个查询的简短版本不起作用?(我是否在概念上遗漏了某些内容,或者我的问题与语法有关?)

table: foo_history: 

id | history::smallint
----------------------------------- 
1  |  {10,20,30,50,40}
Run Code Online (Sandbox Code Playgroud)

这不起作用?

Select id, max(unnest(history)) as vMax from foo_history;
Run Code Online (Sandbox Code Playgroud)

......但这个确实......?

WITH foo as (
    select id, unnest(history) as history 
    from foo_history
)
Select 
    id, max(history) as vMax
From foo 
Group by id;
Run Code Online (Sandbox Code Playgroud)

Cra*_*ger 7

如果您安装intarray模块,它会提供一些额外的数组运算符,让您可以编写您想要的内容,尽管效率有点低:

CREATE EXTENSION intarray;

SELECT id, (sort_desc(history))[1] as vMax
FROM foo_history;
Run Code Online (Sandbox Code Playgroud)

编写要添加的数组的最大函数和最少函数会非常容易intarray,代码非常简单.

否则你只需编写一个SQL函数:

CREATE OR REPLACE FUNCTION array_greatest(anyarray)
RETURNS anyelement LANGUAGE SQL AS $$
SELECT max(x) FROM unnest($1);
$$
Run Code Online (Sandbox Code Playgroud)

并使用:

SELECT id, array_greatest(history) as vMax
FROM foo_history;
Run Code Online (Sandbox Code Playgroud)


Ole*_*aev 5

在PostgreSQL 9.6和8.4中:

SELECT max(x) FROM unnest(ARRAY[1,2,80,3,15,4]) as x;
Run Code Online (Sandbox Code Playgroud)


Dav*_*zer 0

您必须记住,SQL 旨在对数据集进行操作。MAX 函数实际上在第一个示例中确实有效,只是没有按照您的预期工作。它将返回匹配的每一行的最大值。

group by 子句按预期工作,因为您现在聚合到一个集合中,然后从该集合中获取最大值。:)