日期:2014-05-17 浏览次数:20611 次
select id,name,
(select sum(num) from tab2 b ,tab1 a where a.id=b.id and inout='0')as num0,
(select sum(num) from tab2 b ,tab1 a where a.id=b.id and inout='1')as num1
from tab1 a ,tab2 b
where a.id=b.id
group id,name
------解决方案--------------------
declare @t1 table(id int,name varchar(10))
insert into @t1
select 1, 'li' union all
select 2, 'wang' union all
select 3, 'li' union all
select 4, 'zhao'
declare @t2 table(id int,inout int,num int)
insert into @t2
select 1, 0, 100 union all
select 1, 0, 50 union all
select 1, 1, 100 union all
select 1, 1, 200 union all
select 2, 0, 100 union all
select 2, 0, 100 union all
select 2, 1, 50 union all
select 2, 1, 50 union all
select 3, 0, 100 union all
select 3, 0, 200 union all
select 3, 1, 100 union all
select 3, 1, 50
select a.id,
a.name,
sum(case when b.inout=0 then b.num else 0 end) num0,
sum(case when b.inout=1 then b.num else 0 end) num1 from @t1 a
left join @t2 b
on a.id=b.id
group by a.id,a.name
/*
id name num0 num1
----------- ---------- ----------- -----------
1 li 150 300
3 li 300 150
2 wang 200 100
4 zhao 0 0
*/