Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join with a second table containing multiple records, take the latest

I have two tables:

person_id | name
1            name1
2            name2
3            name3

and a second table:

person_id | date     | balance
1           2016-03     1200                    ---- \
1           2016-04     700                     ----  > same person
1           2016-05     400                     ---- /
3           2016-05     4000

Considering that person_id 1 has three record on the second table how can I join the first just by taking the latest record? (that is: balance 400, corresponding to date: 2016-05).

E.g.: query output:

person_id | name    | balance
1           name1     400
2           name2     ---
3           name3     4000

if it's possibile prefer the simplicity over the complexity of the solution

like image 644
giò Avatar asked Sep 06 '25 03:09

giò


2 Answers

A query working for all DB engines is

select t1.name, t2.person_id, t2.balance
from table1 t1
join table2 t2 on t1.person_id = t2.person_id
join
(
    select person_id, max(date) as mdate
    from table2
    group by person_id
) t3 on t2.person_id = t3.person_id and t2.date = t3.mdate
like image 93
juergen d Avatar answered Sep 07 '25 22:09

juergen d


The best way to do this in any database that supports the ANSI standard window functions (which is most of them) is:

select t1.*, t2.balance
from table1 t1 left join
     (select t2.*,
             row_number() over (partition by person_id order by date desc) as seqnum
      from table2 t2
     ) t2
     on t1.person_id = t2.person_id and seqnum = 1;
like image 24
Gordon Linoff Avatar answered Sep 07 '25 23:09

Gordon Linoff