多表连接查询

数据库:MSSQL
表a(id),b(id,zhichu),c(id,shouru)
 a:        b:            c:
 1         1   10        2   30
 2         3   20        3   40
 3         4   20        3   50
 4         3   50        1   60
如何得到:
 id   zhichu    shouru
 1    10           60
 2    0             30
 3    70           90
 4    20           0
 
------------------
create table #a(id int null)
go
create table #b(id int null,zhichu int null)
go
create table #c(id int null,shouru int null)
go
insert into #a values(1)
insert into #a values(2)
insert into #a values(3)
insert into #a values(4)
go
insert into #b values(1,10)
insert into #b values(3,20)
insert into #b values(4,20)
insert into #b values(3,50)
go
insert into #c values(2,30)
insert into #c values(3,40)
insert into #c values(3,50)
insert into #c values(1,60)
go
 
select d.id,d.zhichu,e.shouru
from
( select #a.id as id,
sum(isnull(zhichu,0)) as zhichu
from
#a left join #b on #a.id=#b.id
group by #a.id ) d,
(select #a.id as id,
sum(isnull(shouru,0)) as shouru
from
#a left join #c on #a.id=#c.id
group by #a.id ) e
where d.id=e.id
---------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值