加入第二个 table 包含多条记录,取最新的

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

我有两个 table:

person_id | name
1            name1
2            name2
3            name3

和第二个 table:

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

考虑到 person_id 1 在第二个上有三个记录 table 我怎样才能通过获取最新记录加入第一个? (即:余额400,对应日期:2016-05)

例如:查询输出:

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

如果可能的话,更喜欢简单而不是复杂的解决方案

适用于所有数据库引擎的查询是

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

在任何支持 ANSI 标准 window 函数(其中大部分)的数据库中执行此操作的最佳方法是:

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;