SQL高手来帮忙!
------创建的表如下
table sc (stuid int,subjectid int,score float)
table stu (stuid int,stuname varchar(10),classid int)
table subject (subjectid int,subjectname varchar(10))
我有如下的查询语句
declare @sql varchar (8000),@sql1 varchar (8000)
select @sql='',@sql1=''
select @sql=@sql+',['+subjectname+']=sum(case subjectid when '''+cast(subjectid as varchar(100)) +'''
then score else 0 end)' from(select distinct b.subjectid,c.subjectname
from sc as b inner join subject as c on c.subjectid=b.subjectid) as a order by subjectid
Exec('select 班级=(select classid from stu where stuid=a.stuid)'+@sql+' into # from sc as a group by stuid
select 班级,与考人数=(sum(case 班级 when 班级 then 1 else 0 end))
,Convert(dec(5,1),avg(语文)) 语文平均分
,cast(sum(case when 语文>=90 then 1.0 else 0 end)*100/sum(case 班级 when 班级 then 1 else 0 end) as numeric(5,2)) 语文优秀率
,cast(sum(case when 语文>=60 then 1.0 else 0 end)*100/sum(case 班级 when 班级 then 1 else 0 end) as numeric(5,2)) 语文及格率
,max(语文) 语文最高分
from # group by 班级')
上面的查询我只能得到一科及对语文的统计,我想达到的效果为在@sql中得到有几科,对其的统计也就需要有几科,这主要又是个动态的问题,所以对我这种菜鸟来说有点难
高手们请帮忙啊
把你写的代码共享一下,高分回报(呵呵,至少有100分)