Tom*_*lis 5 postgresql aggregate
我想执行以下操作:
SELECT person, MAX( (date, priority) ) FROM table GROUP BY person;
Run Code Online (Sandbox Code Playgroud)
它将为列中的每个不同值返回一个person
,date
和priority
行person
。的date
和priority
被选择为使得所述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 的东西都是可以接受的,但如果解决方案更标准,那就更好了。
使用窗口函数。
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)
归档时间: |
|
查看次数: |
8716 次 |
最近记录: |