Postgresql extract last row for each id

SqlPostgresqlGreatest N-per-Group

Sql Problem Overview


Suppose I've next data

  id    date          another_info
  1     2014-02-01         kjkj
  1     2014-03-11         ajskj
  1     2014-05-13         kgfd
  2     2014-02-01         SADA
  3     2014-02-01         sfdg
  3     2014-06-12         fdsA

I want for each id extract last information:

  id    date          another_info
  1     2014-05-13         kgfd
  2     2014-02-01         SADA
  3     2014-06-12         fdsA

How could I manage that?

Sql Solutions


Solution 1 - Sql

The most efficient way is to use Postgres' distinct on operator

select distinct on (id) id, date, another_info
from the_table
order by id, date desc;

If you want a solution that works across databases (but is less efficient) you can use a window function:

select id, date, another_info
from (
  select id, date, another_info, 
         row_number() over (partition by id order by date desc) as rn
  from the_table
) t
where rn = 1
order by id;

The solution with a window function is in most cases faster than using a sub-query.

Solution 2 - Sql

select * 
from bar 
where (id,date) in (select id,max(date) from bar group by id)

Tested in PostgreSQL,MySQL

Solution 3 - Sql

I found this as the fastest solution:

 SELECT t1.*
   FROM yourTable t1
     LEFT JOIN yourTable t2 ON t2.tag_id = t1.tag_id AND t2.value_time > t1.value_time
  WHERE t2.tag_id IS NULL

Solution 4 - Sql

Group by id and use any aggregate functions to meet the criteria of last record. For example

select  id, max(date), another_info
from the_table
group by id, another_info

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartaView Question on Stackoverflow
Solution 1 - Sqla_horse_with_no_nameView Answer on Stackoverflow
Solution 2 - SqlVivek S.View Answer on Stackoverflow
Solution 3 - SqlVladislav StoitsovView Answer on Stackoverflow
Solution 4 - SqlAmal TsView Answer on Stackoverflow