交叉求和,请好心人来给小弟弟帮帮忙,就先在此谢过
如下是2个表结构:
表1:
NameID Score
----------- -----------
1001 20
1002 32
表2:
NameID1 Score1 NameID2 Score2 NameID3 Score3
----------- ----------- ----------- ----------- ----------- -----------
1001 5 1002 2 1003 6
1002 6 1003 4 1001 2
问题》:
从表1取一个NameID
然后根据表1的nameid值到表2找出所有nameid相同的和
如:表1:NameID=1001
表2:Score=7(NameID1=1001 NameID3=1001)
以下代码问题是:只显示最后一条记录:
Declare @nameID int
Set @nameID=0
select @nameID=NameID from table1
select @nameID As NameIDIn,Score=Score1+Score2+Score3
FROM
(
select count(*) as total,sum(case when NameID1=@nameID then Score1 else 0 end) As Score1,
sum(case when NameID2=@nameID then Score2 else 0 end) As Score2,
sum(case when NameID3=@nameID then Score3 else 0 end) As Score3
from table2
)
as temp
------解决方案--------------------declare @NameID int
set @NameID = 1001
select NameID = @NameID, Score = ((select isnull(sum(Score1),0) from table2 where NameID1 = @NameID)+(select isnull(sum(Score2),0) from table2 where NameID2 = @NameID)+(select isnull(sum(Score3),0) from table2 where NameID3 = @NameID))
------解决方案--------------------create table t1(
NameID varchar(10),
Score int)
insert t1 select '1001 ',20
union all select '1002 ',32
union all select '1003 ',32
create table t2(
NameID1 varchar(10),
Score1 int,
NameID2 varchar(10),
Score2 int,
NameID3 varchar(10),
Score3 int)
insert t2 select '1001 ',5, '1002 ',2, '1003 ',6
union all select '1002 ',6, '1003 ',4, '1001 ',2
select t1.NameID,sum(t.Score) as ScoreSum from(
select NameID1 as NameID,Score1 as Score from t2
union all
select NameID2,Score2 from t2
union all
select NameID3,Score3 from t2
) t,t1 where t.NameID=t1.NameID group by t1.NameID
--结果:
/*
NameID ScoreSum
---------- -----------
1001 7
1002 8
1003 10
*/