日期:2014-05-16  浏览次数:20549 次

求SQL语句,一个字段中多个ID,怎么对他进行对应的求和
各位高手,我有个问题,具体描述如下,请各位大神帮忙看如何实现:
当RoleId等于0 或等于1 时求number的总和:
id name number
1 li 22
1 li 38
2 wang 50
2 wang 64
3 zhao 70
3 zhao 55

id RoleId
1 0
2 0
3 1

执行完结果如下:
RoleId number
0 174
1 125

------解决方案--------------------


create table A
(
id int,
name varchar(10),
number int
)
insert into A 
select '1', 'li', '22'
union all
select '1', 'li', '38'
union all
select '2', 'wang', '50'
union all
select '2', 'wang', '64'
union all
select '3', 'zhao', '70'
union all
select '3', 'zhao', '55'


create table B
(
id int,
roleid int
)



insert into B
select 1, 0 union all
select 2, 0 union all
select 3, 1




select * from A;

select * from B;


select B.roleid,SUM(A.number) as number  from A inner join B on A.id=B.id
group by
B.roleid

roleid number
0 174
1 125

------解决方案--------------------
select a.RoleId,sum(b.number) number from t1 a join t2 b on a.id=b.id 
where a.RoleId in(0,1)
group by a.RoleId