首页 > 解决方案 > SQL 连接 2 个表以查看差异

问题描述

我有 2 个要加入的表,以便轻松查看它们之间的差异,除以一列(类型)中指定的部分。举个例子:

表格1:

Type1|Data1
Type1|Data2
Type2|Data3

表2:

Type1|Data1
Type2|Data5
Type2|Data6

预期结果:

Type1|Data1|Type1|Data1
Type1|Data2|null|null
Type2|Data3|Type2|Data5
null |null|Type2|Data6

我怎样才能做到这一点?没有唯一标识符我可以绑定这些表

标签: sql

解决方案


我想你想枚举这些值,然后使用full join

select t1.type, t1.data, t2.type, t2.data
from (select t1.*, row_number() over (partition by type order by type) as seqnum
      from t1
     ) t1 full join
     (select t2.*, row_number() over (partition by type order by type) as seqnum
      from t2
     ) t2
     on t1.type = t2.type and t1.seqnum = t2.seqnum;

推荐阅读