根据每个表的重复的ID字段把表a的字段a1和a2,表b字段b1和b2,表c的字段c1和c2合并,并且表a的ID=表b的ID=表c的ID=表D的ID,最后根据表D的ID把结果显示出来。
不知道我说的明白吗?
大家帮忙看看
[此贴子已经被作者于2007-1-10 13:07:45编辑过]
create table a (ID int,a1 int,a2 int) --表a
insert into a select 001,100,150
insert into a select 002,150,200
insert into a select 001,50,60
insert into a select 003,10,10
create table b (ID int,b1 int,b2 int) --表b
insert into b select 001,200,250
insert into b select 002,150,200
insert into b select 002,100,100
insert into b select 003,50,50
drop table c
create table c (ID int,c1 int,c2 int) --表c
insert into c select 001,10,20
insert into c select 002,20,30
insert into c select 003,30,40
insert into c select 003,50,60
drop table d
create table d(ID int) --表d
insert into d select 001
union all select 002
union all select 003
select sum(a.a1) as a1 from a group by a.ID
select d.ID,sum(a.a1) as a1,sum(a.a2) as a2, sum(b.b1) as b1,sum(b.b2) as b2,
sum(c.c1) as c1,sum(c.c2) as c2 from a,b,c,d where a.ID = d.ID
and b.ID = d.ID and c.ID = d.ID group by d.ID
if object_id('a') is not null
drop table a
go
create table a(id varchar(3),a1 int,a2 int)
insert a select '001',100,150
union all
select '002',150,200
union all
select '001',50,60
union all
select '003',10,10
select * from a
if object_id('b') is not null
drop table b
go
create table b (id int,b1 int,b2 int)
insert b select '001',200,250
union all
select '002',150,200
union all
select '002',100,100
union all
select '003',50,50
if object_id('c') is not null
drop table c
go
create table c (id int,c1 int,c2 int)
insert c select '001',10,20
union all
select '002',20,30
union all
select '003',30,40
union all
select '003',50,50
select aa.id,aa.a1,aa.a2,bb.b1,bb.b2,cc.c1,cc.c2 from (select id,sum(a1) as a1 ,sum(a2) as a2 from a group by id) as aa,(select id,sum(b1) as b1 ,sum(b2) as b2 from b group by id) as bb ,
(select id,sum(c1) as c1 ,sum(c2) as c2 from c group by id) as cc where aa.id=bb.id and aa.id=cc.id
结果
id a1 a2 b1 b2 c1 c2
---- ----------- ----------- ----------- ----------- ----------- -----------
001 150 210 200 250 10 20
002 150 200 250 300 20 30
003 10 10 50 50 80 90
(所影响的行数为 3 行)