Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql extract last row for each id

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?

like image 763
Marta Avatar asked Jan 22 '15 09:01

Marta


People also ask

How do I select the second last row in SQL?

Here is the query to get the second last row of a table in MySQL. mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1; The output displays the second last record.

How do I select the last row in SQL?

To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1. Let us first create a table and insert some records with the help of insert command.

What is wildcard in PostgreSQL?

PostgreSQL wildcard is used to match text values from matching patterns. Like operator is used to find matching text values from the table.


2 Answers

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.

like image 79
a_horse_with_no_name Avatar answered Sep 25 '22 05:09

a_horse_with_no_name


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

Tested in PostgreSQL,MySQL

like image 24
Vivek S. Avatar answered Sep 23 '22 05:09

Vivek S.