混合两行的值而不是并集

Mix values from two rows instead of union

我想将行合并在一起,而不是使用例如 union all。我怎样才能做到这一点?通过 ref_id 我知道如何组合。

这是我的示例代码 (postgres):

create table dummy_table1(old_user varchar(20),new_user varchar(20),old_address text,new_address text,Ref_ID varchar(20));

create table dummy_table2(old_user varchar(20),new_user varchar(20),old_address text,new_address text,Ref_ID varchar(20));

insert into dummy_table1 values('dan',null,'Lincoln Street',null,'12bc');
insert into dummy_table1 values('peter',null,'Urban Street',null,'1b99');

insert into dummy_table2 values(null,'Steve',null,'Burban Road','1b99');
insert into dummy_table2 values(null,'barbara',null,'Ocean Drive','12bc');

select * from dummy_table1       
union all 
select * from dummy_table2 

输出:

old_user      new_user     old_address    new_address  ref_id
dan           null         lincoln street null         12bc
peter         null         Urban street   null         1b99
null          steve        null           Burban road  1b99
null          barbara      null           Ocean Drive  12bc

我的目标:

old_user      new_user     old_address    new_address  ref_id
dan           barbara      lincoln street Ocean Drive  12bc
peter         steve        Urban street   Burban road  1b99

如果您确定每个 table 中的 REF_ID 有一个 1:1 匹配,您可以使用 FULL JOIN。例如:

select
  a.old_user,
  b.new_user,
  a.old_address,
  b.new_address,
  coalesce(a.Ref_ID, b.Ref_ID) as ref_id
from dummy_table1 a
full join dummy_table2 b on b.Ref_ID = a.Ref_ID