------解决方案-------------------------------------------------------- 可以,但是这个分档固定下来,否则麻烦点
select name,id,trunc(score/10),count(*) from student_score
group by name,id,trunc(score/10)
上面的语句肯定满足不了楼主的要求。
你都按name,id进行分组了,难道有同一个名字、统一个ID的人得的分数在不同的段中?
------解决方案-------------------------------------------------------- select trunc(score/10) , count(trunc(score/10))
from student_score
group by trunc(score/10)
order by 1
这个方法也是可以的,而且很简洁!
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
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#
---测试数据---
CREATE TABLE 表 (课程名 varchar(20),分数 int)
insert 表
select '语文',80 union all
select '语文',90 union all
select '语文',50 union all
select '语文',65 union all
select '数学',80 union all
select '数学',95 union all
select '数学',100 union all
select '数学',90
---定义存储过程---
if object_id('dbo.ScoreProc') is not null
drop proc dbo.ScoreProc
GO
Create proc dbo.ScoreProc @course varchar(50)
as
begin
select
课程名,
sum(case when 分数 between 0 and 59 then 1 else 0 end) as '60分以下',
sum(case when 分数 between 60 and 74 then 1 else 0 end) as '60-74分',
sum(case when 分数 between 75 and 84 then 1 else 0 end) as '75-84分',
sum(case when 分数 between 85 and 100 then 1 else 0 end) as '85-100分'
from 表
where 课程名=@course
group by 课程名
end
---调用存储过程---
exec ScoreProc '语文'
exec ScoreProc '数学'
---结果---
/**
课程名 60分以下 60-74分 75-84分 85-100分
-------------------- ----------- ----------- ----------- -----------
语文 1 1 1 1
课程名 60分以下 60-74分 75-84分 85-100分
-------------------- ----------- ----------- ----------- -----------
数学 0 0 1 3
**/