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?
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.
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.
PostgreSQL wildcard is used to match text values from matching patterns. Like operator is used to find matching text values from the table.
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.
select * from bar where (id,date) in (select id,max(date) from bar group by id)
Tested in PostgreSQL,MySQL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With