我有以下表格:
Table_A (id,nameA)
------------------
1, nameA1
2, nameA2
Table_Detail (id_A, id_B)
-------------------------
1,1
1,2
1,3
2,2
2,4
Table_B (id_B, nameB, date)
---------------------------
1,nameB1,'02/02/2012'
2,nameB2,'02/02/2012'
3,nameB3,'01/01/2011'
4,nameB4,'03/03/2013'
对于table_A
中的每一行,我想获得具有最大日期的table_B
的名称(但如果有多个,我想获得第一个匹配):
id_A - nameA - NameB_withMaxDate
---------------------------------
1 - nameA1 - nameB1
2 - nameA2 - nameB4
答案 0 :(得分:1)
执行此操作的便捷方法是使用keep
语法:
select a.id, a.name,
max(b.name) keep (dense_rank first order by date desc, id asc) as b_last_name
from a join
table_detail td
on a.id = td.id_a join
b
on b.id = td.id_b
group by a.id, a.name;