超麻烦的问题 查询汇总的问题 急
现在有两张表 数据如
tab1
id shuliang
001 15
001 15
002 22
002 10
003 10
003 2
003 2
006 2
007 20
tab2
id shuliang
001 12
001 12
002 12
002 13
004 45
005 20
想得到如下的结果
id shuliang
001 54
002 57
003 14
004 45
005 20
006 2
007 20
------解决方案--------------------select id,sum(shuliang) shuliang
from (
select * from tab1
union all
select * from tab2
)a
group by id
------解决方案--------------------select t.id,sum(t.shuliang) as shuliang from (select * from tab1 union all select * from tab2) t group by t.id
------解决方案--------------------create table tb1(spid char(3),shuliang int)
create table tb2(spid char(3),shuliang int)
insert into tb1 values( '001 ',15)
insert into tb1 values( '001 ',15)
insert into tb1 values( '002 ',22)
insert into tb1 values( '002 ',10)
insert into tb1 values( '003 ',10)
insert into tb1 values( '003 ',2)
insert into tb1 values( '003 ',2)
insert into tb1 values( '006 ',2)
insert into tb1 values( '007 ',20)
insert into tb2 values( '002 ',12)
insert into tb2 values( '002 ',13)
insert into tb2 values( '001 ',12)
insert into tb2 values( '001 ',12)
insert into tb2 values( '004 ',45)
insert into tb2 values( '005 ',20)
Select
IsNull(A.spid, B.spid) As spid,
IsNull(A.shuliang, 0) + IsNull(B.shuliang, 0) As shuliang
From
(Select spid, SUM(shuliang) As shuliang From tb1 Group By spid) A
Full Join
(Select spid, SUM(shuliang) As shuliang From tb2 Group By spid) B
On A.spid = B.spid
Drop Table tb1, tb2
--Result
/*
spid shuliang
001 54
002 57
003 14
004 45
005 20
006 2
007 20
*/
------解决方案--------------------create table tb1(spid char(3),shuliang int)
create table tb2(spid char(3),shuliang int)
insert into tb1 values( '001 ',15)
insert into tb1 values( '002 ',22)
insert into tb1 values( '015 ',10)
insert into tb1 values( '003 ',2)
insert into tb1 values( '006 ',2)