簡體   English   中英

在oracle中將多個行從一個表復制到另一個表

[英]Copy multiple rows from one table to another table in 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查詢。

謝謝

使用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;

您可以使用merge來“upsert”一行(更新或插入。)合並源可以是子查詢,您可以在其中group by Code並計算Quantity的總和:

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;

SQL Fiddle的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM