日期:2014-05-18  浏览次数:20594 次

如何采用sql语句来实现数据库中多纪录的统计工作!!
最近在作一个实验管理系统,但是最后要涉及到一些成绩的汇总操作,个人感觉非常的麻烦,不知道本站里的朋友是否之前已经解决过类似的问题,能否给小弟一些提示,先在此谢过了,我的表的字段结构如下:
课号,项目号,学号,成绩1,成绩2,成绩3,成绩4,

这个表中有多个课号,每一个课号,代表一个课程,所以每一个课程又会有多个子项目号,每一个子项目里面又会有多大学生参与进去,因此每个学生在某一个项目上肯定有相应的所有的成绩,比如成绩1代表考勤,成绩2代表实验报告,成绩3表示操作水平等等,现在有了这个表了,但是我现在要作一个统计工作。统计的结果如下图所示:
分数档         实验态度       实验理论       操作技能       实验报告       实验总成绩
90-100分     人数多少及百分率。。。。。。都是一样的。。。
80-89           人数及百分率    
。。。。
60分以下       人数及百分率              
因为一门课程是有多个项目组成,对应每一个项目,每一个学生都有四部分的成绩,从成绩1--成绩4,对于最后表中的每一个列都需要作一个统计,比如实验态度这块,我觉得需要先对选了这门课程的所有学生按照课程号为选择条件,进行相应的计算机每个学生的实验态度平均值,但是不知道该怎么算这个东西,因为我对sql语言不是很熟,哪位朋友能否赐教。
还有一个问题就是总的实验成绩又是前面四项所组成的一个整体,但是计算总成绩的时候,我们需要按照比率计算课程中的每一个学生的项目总的成绩,然后在把得到的这个总成绩进行归类,总体感觉转来转去的,特别麻烦,有朋友是否有技巧,解决这个问题。再次拜托大家了。

------解决方案--------------------
写个存储过程

create pr_test
@ 课号 int --查询条件,一次查询一个课号的
as

select 学号,avg(成绩1) as 成绩1,avg(成绩2) as 成绩2,avg(成绩3) as 成绩3,avg(成绩4) as 成绩4
into #
from tablename
group by 学号

declare @总人数 int
select @总人数=count(*) from #
实验理论 操作技能 实验报告 实验总成绩
select 分数档,
max(实验态度人数) as 实验态度人数,max(实验态度百分比) as 实验态度百分比,
max(实验理论人数) as 实验理论人数,max(实验理论百分比) as 实验理论百分比,
max(操作技能人数) as 操作技能人数,max(操作技能百分比) as 操作技能百分比,
max(实验报告人数) as 实验报告人数,max(实验报告百分比) as 实验报告百分比,
max(实验总成绩人数) as 实验总成绩人数,max(实验总成绩百分比) as 实验总成绩百分比
from (
select case when 成绩1> =90 then '90-100分 '
when 成绩1> =80 then '80-89分 '
when 成绩1> =70 then '70-79分 '
when 成绩1> =60 then '60-69分 '
else '60分以下 '
end as 分数档,
count(*) as 实验态度人数,
1.0*count(*)/@总人数 as 实验态度百分比,
cast(null as int) as 实验理论人数,
cast(null as numeric(18,4)) as 实验理论百分比,
cast(null as int) as 操作技能人数,
cast(null as numeric(18,4)) as 操作技能百分比,
cast(null as int) as 实验报告人数,
cast(null as numeric(18,4)) as 实验报告百分比,
cast(null as int) as 实验总成绩人数,
cast(null as numeric(18,4)) as 实验总成绩百分比
from #
group by case when 成绩1> =90 then '90-100分 '
when 成绩1> =80 then '80-89分 '
when 成绩1> =70 then '70-79分 '
when 成绩1> =60 then '60-69分 '
else '60分以下 '
end
union all
select case when 成绩2> =90 then '90-100分 '
when 成绩2> =80 then '80-89分 '
when 成绩2> =70 then '70-79分 '
when 成绩2> =60 then '60-69分 '
else '60分以下 '
end as 分数档,
null as 实验态度人数,
null as 实验态度百分比,
count(*) as 实验理论人数,
1.0*count(*)/@总人数 as 实验理论百分比,
cast(null as int) as 操作技能人数,
cast(null as numeric(18,4)) as 操作技能百分比,
cast(null as int) as 实验报告人数,
cast(null as numeric(18,4)) as 实验报告百分比,
cast(null as int) as 实验总成绩人数,
cast(null as numeric(18,4)) as 实验总成绩百分比
from #
group by case when 成绩2> =90 then '90-100分 '
when 成绩2> =80 then '80-89分 '
when 成绩2> =70 then '70-79分 '
when 成绩2> =60 then '60-69分 '
else '60分以下 '
end
union all
select case when 成绩3> =90 then '90-100分 '
when 成绩3> =80 then '80-89分 '
when 成绩3> =70 then '70-79分 '
when 成绩3> =60 then '60-69分 '
else '60分以下 '
end as 分数档,
null as 实验态度人数,
null as 实验态度百分比,
null as 实验理论人数,
null as 实验理论百分比