假设有如下三个表,test1为主表,test2和test3分别为test1的子表,通过id关联。
test1表 有id 为1,name为 北京仓库
test2表 id为1 的记录有 3条,fqty1分别为 1,2,3
test2表 id为1 的记录有 5条,fqty2分别为 1,2,3,4,5
要求用一条语句求出 test1表中在test2中的sum(fqty1)和sum(fqty2) 记录集比如,上面的结果为id fqty1 fqty2
1 6 15
test1表 有id 为1,name为 北京仓库
test2表 id为1 的记录有 3条,fqty1分别为 1,2,3
test2表 id为1 的记录有 5条,fqty2分别为 1,2,3,4,5
要求用一条语句求出 test1表中在test2中的sum(fqty1)和sum(fqty2) 记录集比如,上面的结果为id fqty1 fqty2
1 6 15
,(select sum(fqty2) from test3 where id=A.id)
from test1 A
test1表 有id 为1,name为 北京仓库
test2表 id为1 的记录有 3条,fqty1分别为 1,2,3
test2表 id为1 的记录有 5条,fqty2分别为 1,2,3,4,5Select a.id,
(Select sum(fqty1) from test2 where id=a.ID) as fqty1,
(Select sum(fqty2) from test3 where id=a.ID) as fqty2
from test1 as a group by a.id
isnull((select sum(fqty1) from test2 where id=a.id),0) as fqty1,
isnull((select sum(fqty2) from test3 where id=a.id),0) as fqty2
from test1 a
order by a.id
select a.id,
isnull((select sum(fqty1) from test2 where id=a.id),0) as fqty1,
isnull((select sum(fqty2) from test3 where id=a.id),0) as fqty2
from test1 a
group by a.id
order by a.id
insert test1
select 1,'北京仓库'
--select * from test1
create table test2(id int,fqty1 int)
insert test2
select 1,1 union all
select 1,2 union all
select 1,3
--select * from test2
create table test3(id int,fqty1 int)
insert test3
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 1,4 union all
select 1,5
--select * from test3select
ID,
name,
fqty1=(select sum(fqty1) from test2 where id=A.id),
fqty2=(select sum(fqty1) from test3 where id=A.id)
from test1 Adrop table test1,test2,test3