日期:2014-05-17  浏览次数:22482 次

数据库查询--统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比
create table Student(S# varchar(10),Sname varchar(10),Sage date,Ssex varchar(10));
create table Course(C# varchar(10),Cname varchar(10),T# varchar(10));
create table Teacher(T# varchar(10),Tname varchar(10));
create table SC(S# varchar(10),C# varchar(10),score decimal(18,1));

有以上4个表,要求得到下面的数据:
统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比

除了最后的百分比,剩下的信息都能通过下面的sql语句获得:

select m.C# , m.Cname , (
  case when n.score >= 85 then '85-100'
  when n.score >= 70 and n.score < 85 then '70-85'
  when n.score >= 60 and n.score < 70 then '60-70'
  else '0-60'
  end) as px, 
  count(1) 
from Course m , sc n
where m.C# = n.C# 
group by m.C# , m.Cname , (
  case when n.score >= 85 then '85-100'
  when n.score >= 70 and n.score < 85 then '70-85'
  when n.score >= 60 and n.score < 70 then '60-70'
  else '0-60'
  end)
order by m.C# , m.Cname , px


请教:如何修改上面的sql,以得到包括百分比在内的所有数据?

------解决方案--------------------
你用count把每种课程每个分数段的数量查出来。。然后总数查出来。。
然后直接用/做除法运算。。就是百分比。。。
你把这个结果 乘以100后面的数都不要了 拼接个%符号就OK了
------解决方案--------------------
count按 课程类别 和 分数阶段统计数量
然后 /总数 就是百分比了
------解决方案--------------------
不知道是不是要这样的效果:
1 01 language 70-85 4 66.67%
2 01 language 0-60 2 33.33%
3 02 maths 85-100 3 50%
4 02 maths 70-85 1 16.67%
5 02 maths 60-70 1 16.67%
6 02 maths 0-60 1 16.67%
7 03 english 85-100 2 33.33%
8 03 english 70-85 2 33.33%
9 03 english 0-60 2 33.33%
SQL code
select t1.*,round(t1.num/t2.all_num*100,2) || '%' 百分比
from 
(select m.C# , m.Cname , (
  case when n.score >= 85 then '85-100'
  when n.score >= 70 and n.score < 85 then '70-85'
  when n.score >= 60 and n.score < 70 then '60-70'
  else '0-60'
  end) as px,  
  count(1) num
from Course m , sc n
where m.C# = n.C#  
group by m.C# , m.Cname , (
  case when n.score >= 85 then '85-100'
  when n.score >= 70 and n.score < 85 then '70-85'
  when n.score >= 60 and n.score < 70 then '60-70'
  else '0-60'
  end)
order by m.C# , m.Cname , px) t1,

(select m.C# , m.Cname ,  
  count(1) all_num
from Course m , sc n
where m.C# = n.C#  
group by m.C# , m.Cname
order by m.C# , m.Cname) t2
where t1.c#=t2.c#