表tab1 如下
ddbh  sl je   bhbj(有变化标记)
------------------- 
A      1  1      1
A      2  2
B      1  1      1
B      3  3      1原来表tab2如下
ddbh  sl je
------------
A      2  2
最后要tab2表的数据
ddbh  sl je
------------
A      3  3
B      4  4
我要做的工作是:
1、将tab2中没有的ddbh,在tab1中有的汇总数插入。
2、如果tab1中某个ddbh,如A的数据增加(如果在tab1中加标志记录一下有改变的数据),tab2重新计算A的数量,不能用sum,只能用2+1=3,因为tab2是个基数。
最后要出tab2的结果是正确的汇总数据。
3、不要整体汇总,只是在tab1中有标记变化的数据才汇总tab2中。
请帮忙,好久不用ORCLEL了
我用的语句感觉很不好:
insert into tab2(je,sl)
select a.ddbh,sum(a.je) zs ,sum(a.sl) ms from tab1 a where a.ddbh not in (select ddbh from tab2)  and a.bhbj=1 group by a.ddbh update tab2 set sl=sl+(select sum(sl) from tab1 where tabl.ddbh=tab2.ddbh and tb1.bhbj=1), je=je+(select sum(je) from tab1 where tabl.ddbh=tab2.ddbh and tb1.bhbj=1),

解决方案 »

  1.   

    是的,我就是感觉用NOT IN 特别不好,怎么解决呢?
      

  2.   

    其实就是个常用的入出库 问题,因为库存是个盘点过的底子,
    你每入出一笔,都要计算一下,只能在原来数据基础上加减,而不能用SUM.
      

  3.   

    update tab2 a set (sl,je)=(select s_sl,s_je from (select ddbh,sum(sl) s_sl,sum(je) s_je from  tab1  where bhbj='1' group by ddbh) b where a.ddbh=b.ddbh);insert into tab2 (select a.ddbh,sum(a.sl),sum(a.je) from tab1 a where not exists (select 1 from tab2 b where a.ddbh=b.ddbh) and a.bhbj='1' group by a.ddbh);
      

  4.   


    那你用not exists 吧!
      

  5.   

    谢谢,您的INSERT语句比较好,但UPDATE 语句我是要累加的,是在原来表TAB2的基础上增加TAB1的数据(比如有新的入库)。
      

  6.   


    1、将tab2中没有的ddbh,在tab1中有的汇总数插入。 
    insert into tab2 (select t1.ddbh, sum(t1.sl), sum(t1.je) from tab1 t1 where not exist (select 1 from tab2 t2 where t2.ddbh=t1.ddbh))2、如果tab1中某个ddbh,如A的数据增加(如果在tab1中加标志记录一下有改变的数据),tab2重新计算A的数量,不能用sum,只能用2+1=3,因为tab2是个基数。 
    最后要出tab2的结果是正确的汇总数据。
    update tab2 t2 set(sl,je) (select t2.sl+temp.sl, t2.je+temp.sl from (select sum(sl) sl, sum(je) je ddbh from tab1 t1 where t1.bhbj=1 and t2.bhbj=t1.bhbj) temp)时间不够,还没有测试过,你看这个逻辑对不对