求一条sql语句,在线等。
A表 id,subid,paysubid
B表 id,subid,itemname,funds
C表 id,paysubid,payitemname,payfunds
A表数据: 1,3126,3319
B表数据: 1,3126,水费,7600
B表数据: 2,3126,电费,3000
C表数据:1,,3319 ,水费,200
C表数据:2,,3319 ,电费,300
C表数据:3,,3319 ,水费,500
C表数据:4,,3319 ,电费,300
C表数据:5,,3319 ,办公费,1000
想求出来的数据是
---------------------------
水费 7600 700
电费 3000 600
办公费 0 1000
语句应该怎么写呢。
[解决办法]
create table #A( id int identity(1,1), subid int, paysubid int)create table #B( id int identity(1,1), subid int, itemname nvarchar(50), funds int)create table #C( id int identity(1,1), paysubid int, payitemname nvarchar(50), payfunds int)insert into #Aselect 3126,3319 union allselect 3127,3320 insert into #Bselect 3126,'水费',7600 union allselect 3126,'电费',3000 union allselect 3127,'水费',1200 union allselect 3127,'津贴补贴',5000 union allselect 3127,'工资福利支出',2000insert into #Cselect 3319 ,'水费',200 union allselect 3319,'电费',300 union allselect 3319 ,'水费',500 union allselect 3319 ,'电费',300 union allselect 3319,'办公费',1000 union allselect 3320,'水费',100 union allselect 3320,'津贴补贴',200 union allselect 3320,'水费',500 union allselect 3320,'工资福利支出',900select c.payitemname,isnull(b.funds,0),c.payfunds,c.paysubid from (select paysubid,payitemname,sum(payfunds)payfunds from #Cgroup by paysubid,payitemname)cjoin #A a on a.paysubid=c.paysubidleft join (select subid,itemname,SUM(funds)funds from #Bgroup by subid,itemname) b on b.subid=a.subid and b.itemname=c.payitemname order by c.paysubiddrop table #Adrop table #Bdrop table #C办公费 0 1000 3319电费 3000 600 3319水费 7600 700 3319工资福利支出 2000 900 3320津贴补贴 5000 200 3320水费 1200 600 3320