在oracle中将多个行从一个表复制到另一个表

时间:2013-03-27 07:45:04

标签: sql oracle

表1

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查询。

由于

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

您可以使用merge“upsert”一行(更新或插入。)合并源可以是子查询,您可以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.