比我有2个表 a,ba是这样的kpbh    totalsum
0001
0002
0003
0004b是这样的kpbh     totalsum
0001        1
0001        2
0002        3
0002        4
0003        5
0003        6
0004        7
0004        8
0005        9现在我想更新表a 的totalsum 等于 b相同kpbh 的求和
我的语句应该怎么写?

解决方案 »

  1.   

    update a set totalsum=((select sum(totalsum) from b where  a.kpbh=b.kpbh))这个语句和下面的有何不同  +个括号就行了?
    update a set totalsum=(select sum(totalsum) from b where  a.kpbh=b.kpbh)
      

  2.   


    --1
    update a
       set totalsum =(select sum(totalsum ) from b where b.kpbh = a.kpbh)
     where exists(select 1 from a,b where a.kpbh=b.kpbh);--2
    merge into a
         using (select kpbh,sum(totalsum) totalsum from b group by kpbh) tmp
           on(a.kpbh = tmp.kpbh)
     when matched then
       update a.totalsum = tmp.totalsum;--3
    update(
      select a.kpbh,a.totalsum,sun(b.totalsum) totalsum_b
        from a,b
       where a.kpbh = b.kpbh
      group by a.kpbh,a.totalsum)
    set totalsum = totalsum_b;--第三个没有验证,不知道带聚合的情况好不好用
      

  3.   


    ++ SO 帅第一个sql其实不用写WHERE 条件吧?第二个SQL 漏掉了UPDATE SET 关键字第三个不知.
      

  4.   

    1、针对此需求可以不写
    2、你说的对 set 漏写了,领会意思
    3、语法oracle绝对支持,但是带聚合函数的好不好用,需要验证。
      

  5.   


    其实第二个,我是看你写了之后,又练了一会才学会了MERGEINTO 的用法,感谢分享!