Oracle 11g:用表B中的最新记录替换表A中的记录

时间:2018-12-04 06:14:15

标签: sql oracle11g

我有2个表,表A和表B。我需要返回表A中的所有记录,但是如果ID存在,我需要将COL_A替换为TABLE_B中最新的COL_A值。

TABLE_A                       TABLE_B
ID COL_A                      A_ID   COL_A  CREATED_DATE
1  AAA                        1      AA1    1/11/18
2  BBB                        1      AA2    1/12/18
3  CCC                        3      CC1    1/12/18

预期输出:

ID COL_A
1  AA2
2  BBB
3  CC1

我可以使用Oracle 12c执行以下操作,但不能在11g上执行以下操作。需要有关如何查询11g的帮助吗?

select ID, 
NVL((select * from (select FIRST_VALUE(COL_A) OVER (ORDER BY CREATED_DATE DESC) from TABLE_B WHERE A_ID=A.ID) where ROWNUM=1),COL_A) AS COL_A
from TABLE_A A

2 个答案:

答案 0 :(得分:0)

您缺少2个表和一个用于查询最大日期的子查询之间的联接:

select a.ID, NVL(b.col_a, a.col_a) 
from TABLE_A a left outer join TABLE_B b 
on a.id = b.a_id 
and b.created_date = 
(select max(innerB.createdDate) from Table_B innerB where innerB.a_id = a.id);

尝试一下,如果出现错误,请告诉我

答案 1 :(得分:0)

我倾向于使用窗口功能:

select a.id, coalesce(b.col_a, a.col_a) as col_a
from a left join
     (select b.*,
             row_number() over (partition by b.a_id order by b.created_date) as seqnum
      from b
     ) b
     on b.a_id = a.id and b.seqnum = 1;

这似乎比使用join 相关子查询的版本简单得多。