请问这个怎么写?谢谢
表a 表b
ID 申请费 退出费 ID 申请 退出
1 1 1 1 1 0
1 2 2 2 0 1
2 3 3
2 4 4
表c
ID 申请 退出 申请费(汇总) 退出费(汇总)
1 1 0 3 0
2 0 1 0 7
请问怎么才能根据表a,表b,得到表c。谢谢。
[解决办法]
select b.id,b.申请,b.退出, sum(case when b.申请=1 then a.申请费 else 0 end) 申请费, sum(case when b.退出=1 then a.退出费 else 0 end) 退出费from a join b on a.id = b.idgroup by b.id,b.申请,b.退出
[解决办法]
select b.id,b.申请,b.退出,a.申请费,a.退出费
from b inner join (select id,count(*) from a group by a.id)TMP on b.id=tmp.id
不行就建个临时表过度下
[解决办法]
create table a(ID int,申请费 int,退出费 int)create table b(ID int,申请 int,退出 int)insert into a values(1 ,1 ,1) insert into a values(1 ,2 ,2) insert into a values(2 ,3 ,3)insert into a values(2 ,4 ,4 ) insert into b values(1 ,1 ,0)insert into b values(2 ,0 ,1)goselect b.* , [申请费(汇总)] = isnull((select sum(申请费) from a where a.id = b.id and b.申请 <> 0),0), [退出费(汇总)] = isnull((select sum(退出费) from a where a.id = b.id and b.退出 <> 0),0)from bdrop table a , b/*ID 申请 退出 申请费(汇总) 退出费(汇总) ----------- ----------- ----------- ----------- ----------- 1 1 0 3 02 0 1 0 7(所影响的行数为 2 行)*/
[解决办法]
上面的错了,应该是这样
select b.id,b.申请,b.退出,TMP.申请费,TMP.退出费
from b inner join (select id,sum(申请费),sum(退出费) from a group by a.id)TMP on b.id=tmp.id
[解决办法]
declare @表a table (ID int,申请费 int,退出费 int)insert into @表aselect 1,1,1 union allselect 1,2,2 union allselect 2,3,3 union allselect 2,4,4declare @表b table (ID int,申请 int,退出 int)insert into @表bselect 1,1,0 union allselect 2,0,1select b.id,b.申请,b.退出, [申请费(汇总)]=sum(a.申请费*b.申请), [退出费(汇总)]=sum(a.退出费*b.退出) from @表b b left join @表a a on a.id=b.id group by b.id,b.申请,b.退出/*id 申请 退出 申请费(汇总) 退出费(汇总)----------- ----------- ----------- ----------- -----------1 1 0 3 02 0 1 0 7*/