How to get all rows with the maximum date from a query in PostgreSQL?
For example, if I got the following rows:
1, 1, '2014-05-27'
2, 2, '2014-05-26'
3, 3, '2014-05-26'
4, 4, '2014-05-25'
5, 5, '2014-05-27'
I need to get this result:
1, 1, '2014-05-27'
5, 5, '2014-05-27'
Only the ones with the maximum date - but all of those. This gets it done by repeating the query in a subquery:
SELECT *
FROM table
WHERE field_1 = '1'
AND date_1 = (SELECT MAX(date_1) FROM table WHERE field_1 = '1');
Is there a simpler / faster way (without repeating the query)?
Maybe with the HAVING
clause?