select tem.id,tem.id2,sum(aa.数量) 购进,sum(bb.数量) 消耗,sum(cc.数量) 销售
from (select distinct ID,ID2 from @购进 distinct union select ID,ID2 from @消耗 union select ID,ID2 from @销售) tem
left join @购进 aa on aa.id=tem.id and aa.id2=tem.id2 
left join @消耗 bb on bb.id=tem.id and bb.id2=tem.id2 
left join @销售 cc on cc.id=tem.id and cc.id2=tem.id2
group by tem.id,tem.id2
order by tem.id,tem.id2

解决方案 »

  1.   

    select tem.id,tem.id2,sum(aa.数量) 购进,sum(bb.数量) 消耗,sum(cc.数量) 销售
    from (select distinct ID,ID2 from @购进 distinct union select ID,ID2 from @消耗 union select distinct ID,ID2 from @销售) tem
    left join  @购进 aa on aa.id=tem.id and aa.id2=tem.id2 
    left join @消耗 bb on bb.id=tem.id and bb.id2=tem.id2 
    left join @销售 cc on cc.id=tem.id and cc.id2=tem.id2
    group by tem.id,tem.id2
    order by tem.id,tem.id2
      

  2.   

    select tem.id,tem.id2,sum(aa.数量) 购进,sum(bb.数量) 消耗,sum(cc.数量) 销售
    from (select distinct ID,ID2 from @购进 distinct union select ID,ID2 from @消耗 union select distinct ID,ID2 from @销售) tem
    left join (select id,id2,sum(数量) as 数量 from  @购进 group by id,id2) aa on aa.id=tem.id and aa.id2=tem.id2 
    left join (select id,id2,sum(数量) as 数量 from  @消耗 group by id,id2) bb on bb.id=tem.id and bb.id2=tem.id2 
    left join (select id,id2,sum(数量) as 数量 from  @销售 group by id,id2) cc on cc.id=tem.id and cc.id2=tem.id2
    group by tem.id,tem.id2
    order by tem.id,tem.id2
      

  3.   

    declare @购进 table(ID varchar(2),ID2 varchar(2),数量 int)
    insert  @购进 values ('A' ,'a',     10)
    insert  @购进 values ('A' ,'a',     20)
    insert  @购进 values ('C', 'a' ,    30)中有ID,ID2重复的直所以会出错
      

  4.   

    谢谢caiyunxia(monkey)大侠的帮助,但你的程序通不过呀,有语法错误,希望再帮我改改,谢谢啦!!
      

  5.   

    select tem.id,tem.id2,sum(aa.数量) 购进,sum(bb.数量) 消耗,sum(cc.数量) 销售
    from (select distinct ID,ID2 from @购进 union select  distinct  ID,ID2 from @消耗 union select distinct ID,ID2 from @销售) tem
    left join (select id,id2,sum(数量) as 数量 from  @购进 group by id,id2) aa on aa.id=tem.id and aa.id2=tem.id2 
    left join (select id,id2,sum(数量) as 数量 from  @消耗 group by id,id2) bb on bb.id=tem.id and bb.id2=tem.id2 
    left join (select id,id2,sum(数量) as 数量 from  @销售 group by id,id2) cc on cc.id=tem.id and cc.id2=tem.id2
    group by tem.id,tem.id2
    order by tem.id,tem.id2
      

  6.   

    实际情况中ID,ID2是有可能重复的,所以只能这样考虑了。
      

  7.   

    谢谢 caiyunxia(monkey) 大侠,你的代码通过了。
      

  8.   

    select *,(select sum(数量) from @购进 where id=tem.id and id2=tem.id2) 购进,(select sum(数量) from @消耗 where id=tem.id and id2=tem.id2) 消耗,(select sum(数量) from @销售 where id=tem.id and id2=tem.id2) 销售 from (select ID,ID2 from @购进 union select ID,ID2 from @消耗 union select ID,ID2 from @销售) tem
      

  9.   

    谢谢,大力斑主及monkey大侠的帮助使我长进不少。接分吧!