2012-03-22 62 views
0

我有一個模式,它看起來像這樣從DB2行中的一個表中的列遷移數據的其他表

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錯誤代碼407。我嘗試使用IFNULL,COALESCE,但似乎沒有工作。我知道這是一個必須多次解決的問題,但無法在任何地方直接得到答案。

回答

1

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); 
相關問題