【问题标题】:Copy multiple rows from one table to another table in oracleoracle 将一张表的多行复制到另一张表
【发布时间】:2013-03-27 07:45:04
【问题描述】:

表 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 中按代码分组获取 sum(Quantity),如果代码存在则在表 2 中更新,否则插入新行。剩余的行保留在表 2 中。如何为以下场景编写 oracle plsql 查询。

谢谢

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用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.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 2018-06-24
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多