我有2个具有相同结构的SQL表。一个是第二个版本的更新版本。如何合并2以使新表的记录优先于另一个,并且仍然包含在较新表中没有更新的记录?
原始表ID(是主键):
ID, NAME, ADDRESS
11 AL 1 main street
22 BOB 2 main street
33 CHAZ 3 main street
更新表
ID, NAME, ADDRESS
11 AL 99 maple street
22 BOB 2 main street
我想要的结果
ID, NAME, ADDRESS
11 AL 99 maple street
22 BOB 2 main street
33 CHAZ 3 main street
感谢, MC
答案 0 :(得分:5)
coalesce
将返回第一个非null值。结合left join
,这将首先使用新数据,如果为空,则使用旧数据。
select coalesce(u.id, o.id) as id,
coalesce(u.name, o.name) as name,
coalesce(u.address, o.address) as address
from original_table o
left join updated_table u on u.id = o.id
答案 1 :(得分:2)
15 data _null_;
16 run;
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
答案 2 :(得分:0)
尝试结合:
Select id as uid, name, address from new_table
Union
Select id, name, address from old_table
Where id not in (select id from new_table)
另外,请不要将id用作列名。非常糟糕的主意。