2013-03-27 95 views
2

表1從一個表到另一表複製的多個行中的Oracle

Item ---- Qauntity ---- Code 
123 1 --- 10  --- 123 
123 2 --- 20  --- 123 
123 3 --- 30  --- 123 
653 3 --- 60  --- 345 
653 2 --- 30  --- 345 
653 4 --- 20  --- 345 
967 3 --- 10  --- 967 
967 2 --- 20  --- 967 
967 1 --- 30  --- 967 

表2:

Code -- Qauntity 
123 --  40 
345 --  30 
444 --  10 
234 --  20 
653 --  60 

我需要由代碼從表1和更新以獲得與組總和(數量)在表2中,如果代碼存在,則插入一個新行。剩餘的行保留在表2中。如何爲以下方案編寫oracle plsql查詢?

感謝

回答

0

使用MERGE你能做到這一點

merge into table2 t2 using (select code, quantity from table1) t1 on (t2.code = t1.code) 
when not matched then insert (code,quantity) values (t1.code,t1.qty) 
when matched then update set quantity = quantity+t1.quantity; 
+0

謝謝Ravindra – 2013-03-27 18:38:28

0

您可以使用merge爲「更新插入一排」(更新或插入)合併源可以是一個子查詢,你可以group by Code和計算數量的總和:

merge into Table2 t2 
using (
     select Code 
     ,  sum(Quantity) as SumQuantity 
     from Table1 
     group by 
       Code 
     ) t1 
on  (t1.Code = t2.Code) 
when not matched then 
     insert (Code, Quantity) 
     values (t1.Code, t1.SumQuantity) 
when matched then 
     update set Quantity = t1.SumQuantity; 

Example at SQL Fiddle.

+0

謝謝Andomar – 2013-03-27 18:37:54

相關問題