0

I have a table containing, for example, this data:

id | value | name   | date
1  | 1     | 'one'  | 2015-01-02
2  | 1     | 'two'  | 2015-02-03
3  | 2     | 'three'| 2014-01-03
4  | 2     | 'four' | 2014-01-02

I want for each distinct value, the name of the row with the latest date. So:

value | name   | date
1     | 'two'  | 2015-02-03
2     | 'three'| 2014-01-03

I currently have this query: SELECT value, MAX(date) FROM table GROUP BY value, which gives me the value and date columns I'm looking for. How do I modify the query to add the name field? Simply adding it to the SELECT clause won't work, as Postgres will (understandably) complain I have to add it to the GROUP BY clause. But doing so will add it to the uniqueness check, and my query will return all 4 rows. All I need is the name of the row where it found the latest date.

2

2 Answers 2

1

distinct on() is the most efficient way to do this with Postgres

select distinct on (value) id, value, name, date
from the_table
order by value, date;

SQLFiddle example: http://sqlfiddle.com/#!15/dff68/1

1
  • Perfect, this is exactly what I needed!
    – user8681
    Nov 19, 2015 at 15:03
0

This will give you all required fields:

select t1.* from table t1 
inner join (
  SELECT value, MAX(date) as date FROM table GROUP BY value
 )t2 on t1.date=t2.date;

SQL Fiddle: http://sqlfiddle.com/#!15/9491f/2

2
  • I don't think so. I want a MAX(date), not MAX(id), meaning I can't do the join you're proposing.
    – user8681
    Nov 17, 2015 at 17:56
  • What if you have two same date for single value? Nov 17, 2015 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.