Sql Db2将数据从一个表中的行迁移到另一个表中的列
我有一个这样的模式Sql Db2将数据从一个表中的行迁移到另一个表中的列,sql,db2,data-migration,Sql,Db2,Data Migration,我有一个这样的模式 table 1 ------- ID TYPE VALUE ============== 1 A 10 1 B 200 2 A 20 2 B 500 table 2 ------------- ID typeA typeB ============== 1 10 200 2 20 500 我的迁移脚本是 update table2 set typeA = (select t1.value from table1 t1 where t1.ID = table2.ID a
table 1
-------
ID TYPE VALUE
==============
1 A 10
1 B 200
2 A 20
2 B 500
table 2
-------------
ID typeA typeB
==============
1 10 200
2 20 500
我的迁移脚本是
update table2 set typeA = (select t1.value from table1 t1
where t1.ID = table2.ID and t1.type = 'A'),
typeB = (select t1.value from table1 t1 where t1.ID = table2.ID and t1.type='B');
现在,当每个id有两个类型时,它可以正常工作,如果缺少某个类型的行,则会出现sql错误代码。我尝试使用IFNULL、COALESCE,但似乎没有任何效果。我知道这个问题已经解决了很多次,但在任何地方都找不到直接的答案。
COALESCE
应该适合您,这会给您带来错误吗
update table2 t2
set typeA = COALESCE((select t1.value
from table1 t1
where t1.ID = t2.ID
and t1.type = 'A'), 0),
typeB = COALESCE((select t1.value
from table1 t1
where t1.ID = t2.ID
and t1.type='B'), 0);