首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

高分求解高难度sql语句(对小弟来说),请各位老大帮忙!解决思路

2012-01-23 
高分求解高难度sql语句(对小弟来说),请各位老大帮忙!表ProScore如下:StuIdStuNameProNameScore1a语文701a

高分求解高难度sql语句(对小弟来说),请各位老大帮忙!
表ProScore如下:
StuId       StuName   ProName   Score
1                     a               语文       70
1                     a               数学       70
1                     a               英语       70
2                     b               语文       80
2                     b               数学       80
2                     b               英语       80
3                     c               语文       90
3                     c               数学       90
3                     c               英语       90

我用下面的SQL语句:
declare   @s   varchar(4000)  
set   @s= 'select   StuId   '+ '学号 '+ ',StuName   '+ '姓名 '  
select   @s=@s+ ',sum(case   ProName   when   ' ' '+ProName+ ' ' '   then   Score   else   0   end)   [ '+ProName+ '] '
from(select   distinct   ProName   from   ProScore)   as   a  
set   @s=@s+ '   from   ProScore   group   by   StuId,StuName '  
exec(@s)
实现了如下表的显示:
学号         姓名           数学         英语         语文
1                 a               70               70             70
2                 b               80               80             80
3                 c               90               90             90

请问应该怎样修改我的SQL语句才能实现如下显示呢?
学号         姓名           数学         英语         语文       总分       平均分
1                 a               70               70             70         210           70
2                 b               80               80             80         240           80


3                 c               90               90             90         270           90
其中ProName字段的记录值是动态增加的,也就是说不一定只有“数学”、“英语”、“语文”这三个记录值。
小弟在这里先谢谢了!^_^



[解决办法]
实现是可以,但是效率不高,在动态sql中再加上,(select sum(score) from proscore as a where a.stuid = proscore.stuid) as 总分,,((select sum(score) from proscore as a where stuid = proscore.stuid)/(select count(distinct proname) from proscore as b where b.stuid=proscore.stuid)) as 平均分.


另外可在DataTable中计算
[解决办法]
declare @s varchar(4000) set @s= 'select StuId '+ '学号 '+ ',StuName '+ '姓名 ' select @s=@s+ ',sum(case ProName when ' ' '+ProName+ ' ' ' then Score else 0 end) [ '+ProName+ '] 'from(select distinct ProName from ProScore) as a set @s=@s+ ' from ProScore group by StuId,StuName ' set @s = 'select * ,(select sum(Score) from ProScore as a where a.StuId = aa.学号) as 总分,((select sum(Score) from ProScore as a where a.StuId = aa.学号) / (select count(distinct ProName) from ProScore as b where b.StuId= aa.学号) ) as 平均分from ( ' +@s + ' ) as AA 'exec(@s)

热点排行