2015-01-22 14 views
12

Supponiamo che io ho prossimi datiPostgreSQL estrarre ultima riga per ogni ID

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 

che voglio per ogni estratto id informazioni:

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

Come potrei gestire che?

risposta

19

Il modo più efficace è quello di utilizzare Postgres' operatore distinct on

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

Se si desidera una soluzione che funziona su basi di dati (ma è meno efficiente) è possibile utilizzare una funzione di finestra:

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; 

La soluzione con una funzione finestra è nella maggior parte dei casi più veloce rispetto all'utilizzo di una sottoquery.

+0

grazie, ho solo bisogno che !!! –

0

Raggruppare per id e utilizzare qualsiasi funzione aggregata per soddisfare i criteri dell'ultimo record. Per esempio

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

di nuovo questo non darà l'output effettivo –

+0

Cosa mi manca qui? –

+0

Hai testato la tua selezione ??? –

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

Testato in PostgreSQL, MySQL

Problemi correlati