我有两张桌子:
TABLE 1 ID Value ValueFromTable2 1 A NULL 1 B NULL 1 C NULL 1 D NULL 2 E NULL 2 F NULL TABLE 2 ID Value 1 A1 1 A2 1 A3 2 BOB 2 JIM
我想用表2的值更新表1,以便产生以下行:
TABLE 1 ID Value ValueFromTable2 1 A A1 1 B A2 1 C A3 1 D NULL 2 E BOB 2 F JIM
命令它不是非常重要。也就是说,我并不担心A与A1配对或B与A2配对。我只需要表2中的值列中的完整数据集即可从表1中获得。
请指教!
答案 0 :(得分:1)
您需要一把钥匙才能加入他们。隐式密钥是排序。您可以使用row_number()
:
select coalesce(t1.id, t2.id) as id,
t1.value, t2.value
from (select t1.*, row_number() over (partition by id order by (select NULL)) as seqnum
from table1 t1
) t1 full outer join
(select t2.*, row_number() over (partition by id order by (select NULL)) as seqnum
from table2 t2
) t2
on t1.id = t2.id and t1.seqnum = t2.seqnum;
使用full outer join
时,无论哪个值都是较长的列表,都会显示所有值。