各位老大:
我有一个查询的SQL语句请教,希望能够用一条SQL语句得到结果,问题如下:表X:
A     B     C   D
------------------
北京 广州 1000  10
北京 深圳 1200  20
北京 上海 500   30
北京 天津 300   40
北京 河南 800   20
表Y:
A     B
----------
北京 深圳
北京 上海
表Z:
A     B     C    D
------------------
北京 广州  200   10
北京 上海 -100  -10
北京 四川  800   50目的:从表X中去除表Y中关键字相同的数据,再加上表Z中的数据,关键字相同的要累计(A,B为关键字)
得到如下结果:A     B     C   D
------------------
北京 广州 1200  20
北京 上海 400   20
北京 河南 800   20
北京 四川 800   50

解决方案 »

  1.   

    Y表中打错了,Y表应该是:表Y:
    A     B
    ----------
    北京 深圳
    北京 天津
      

  2.   

    select a,b,sum(c) as c,sum(d) as d from 
    (select * from x full join z on x.a=z.a and x.b=z.b ) t
    where not exits (select 1 from y where y.a=t.a and y.b=t.b)
    group by a,b
      

  3.   

    select * from 
    (
    select a, b, sum(c) c, sum(d) d from (
    select * from x
    union all
    select * from z) t1
    group by a, b
    ) t2 
    where not exists (select 1 from y where t2.a=y.a and t2.b=y.b)
      

  4.   

    --上面写错了
    select a,b,sum(c) as c,sum(d) as d from 
    (select * from x union all select * from z ) t
    where not exits (select 1 from y where y.a=t.a and y.b=t.b)
    group by a,b