patternsqlMinor
Can I perform a MAX over a pair of columns?
Viewed 0 times
cancolumnsperformmaxoverpair
Problem
I would like to execute the following:
It would return a
As an example, running the query on this table
should result in
Postgres complains about this particular attempt:
Is there a way that I can achieve this? Anything that works with Postgres will be acceptable but if a solution is more standard then so much the better.
SELECT person, MAX( (date, priority) ) FROM table GROUP BY person;It would return a
person, date and priority row for each distinct value in the person column. The date and priority are chosen such that the date value is maximised, and the maximum priority that occurs on that date is chosen.As an example, running the query on this table
person | date | priority
---------------------------------
1 | '2014-01-01' | 10
1 | '2014-01-02' | 2
1 | '2014-01-02' | 3should result in
person | date | priority
---------------------------------
1 | '2014-01-02' | 3Postgres complains about this particular attempt:
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.Is there a way that I can achieve this? Anything that works with Postgres will be acceptable but if a solution is more standard then so much the better.
Solution
Use a windowing function.
SQL Fiddle link for you to play with.
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;SQL Fiddle link for you to play with.
Code Snippets
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;Context
StackExchange Database Administrators Q#78193, answer score: 7
Revisions (0)
No revisions yet.