我可以在一对列上执行 MAX 吗?

Tom*_*lis 5 postgresql aggregate

我想执行以下操作:

SELECT person, MAX( (date, priority) ) FROM table GROUP BY person;
Run Code Online (Sandbox Code Playgroud)

它将为列中的每个不同值返回一个person,datepriorityperson。的datepriority被选择为使得所述date值被最大化,且最大priority发生在该日期被选择。

例如,在此表上运行查询

person |     date     | priority
---------------------------------
   1   | '2014-01-01' |    10
   1   | '2014-01-02' |     2
   1   | '2014-01-02' |     3
Run Code Online (Sandbox Code Playgroud)

应该导致

person |     date     | priority
---------------------------------
   1   | '2014-01-02' |     3
Run Code Online (Sandbox Code Playgroud)

Postgres 抱怨这种特殊的尝试:

ERROR:  function max(record) does not exist
HINT:  No function matches the given name and argument types.
You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一目标?任何适用于 Postgres 的东西都是可以接受的,但如果解决方案更标准,那就更好了。

Phi*_*lᵀᴹ 7

使用窗口函数。

select * from (
select person, date, priority, row_number() over(partition by person order by date desc,priority desc) as p
from table
) as foo
where p=1;
Run Code Online (Sandbox Code Playgroud)

SQL Fiddle 链接供您使用。


小智 7

这是否符合您的需求?

SELECT DISTINCT ON (person)
       person, date, priority
  FROM table
 ORDER BY person, date DESC, priority DESC;
Run Code Online (Sandbox Code Playgroud)