求SQL语句:计算每个成绩段的学生人数

goodsong 2004-09-11 07:56:38
table1
number name score
100001 aaaa 10
100002 aaab 20
100003 aaac 15
... ... ...

成绩为0-100
分成20段
我知道可以每次求一段
select count(*)
from table1
where score>=0 and score <5

select count(*)
from table1
where score>=5 and score <10
我要用存储过程一次求出所有段的人数,有没有什么效率比较高的方法
另外想问一下,调用存储过程的开销是不是很大?比如每次返回一个成绩段的人数和把所有成绩段的人数求出后一次返回,哪个更好?为什么?
不知问题说清楚没有,感谢大家的帮助
...全文
957 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
彩练当空 2004-09-11
  • 打赏
  • 举报
回复
写得好,收藏
goodsong 2004-09-11
  • 打赏
  • 举报
回复
谢谢各位老大!
ouyld 2004-09-11
  • 打赏
  • 举报
回复
zjcxc 2004-09-11
  • 打赏
  • 举报
回复
当然,上面的也是一条sql语句而已,也可以封装成存储过程,也可以做为一个普通sql语句执行.

存储过程的优势体现在预编译上,仅在第一次执行时需要编译,以后直接执行
而普通sql语句每次执行都要经过编译处理

另外,存储过程还可以减少网络传输量,不需要像执行普通sql语句那样,需要把要执行的sql语句在执行时,由客户端传递到服务器.
zjcxc 2004-09-11
  • 打赏
  • 举报
回复
--个人觉得这样统计吧,你的分类段是固定的,这样的写法,效率上应该是比冒牌的高
--如果某个分数段没有人,也会把该分数段显示出来.

select 成绩段=b.成绩段,人数=count(a.score)
from table1 a right join(
select 成绩段='0--5',a=0,b=5
union all select '5--10',5,10
union all select '10--15',10,15
union all select '15--20',15,20
union all select '20--25',20,25
union all select '25--30',25,30
union all select '30--35',30,35
union all select '35--40',35,40
union all select '40--45',40,45
union all select '45--50',45,50
union all select '50--55',50,55
union all select '55--60',55,60
union all select '60--65',60,65
union all select '65--70',65,70
union all select '70--75',70,75
union all select '75--80',75,80
union all select '80--85',80,85
union all select '85--90',85,90
union all select '90--95',90,95
union all select '95--100',95,101
)b on a.score>=b.a and a.score<b.b
group by b.成绩段
zicxc 2004-09-11
  • 打赏
  • 举报
回复
这个问题一个sql语句能搞定,用存储过程和不用存储过程的效率差不多
当然是一次返回所有分数段的效率高

venket 2004-09-11
  • 打赏
  • 举报
回复
当然是用存储过程好的多拉
因为他可以减少网络流量
你想向你传一条指令就能执行很多的指令
就可以明白拉!!
zicxc 2004-09-11
  • 打赏
  • 举报
回复
还有个问题100分归到了100--105了,变成有21段了,特殊处理一下,再加个排序:

select case when score=100 then '95--100' else cast(cast(score as int)/5*5 as varchar(10))+'--'+cast((cast(score as int)/5+1)*5 as varchar(10)) end as 分数段,
count(*) as 人数
from table1
group by case when score=100 then '95--100' else cast(cast(score as int)/5*5 as varchar(10))+'--'+cast((cast(score as int)/5+1)*5 as varchar(10)) end
order by min(score)
zicxc 2004-09-11
  • 打赏
  • 举报
回复
更正:
select cast(cast(score as int)/5*5 as varchar(10))+'--'+cast((cast(score as int)/5+1)*5 as varchar(10)) as 分数段,
count(*) as 人数
from table1
group by cast(cast(score as int)/5*5 as varchar(10))+'--'+cast((cast(score as int)/5+1)*5 as varchar(10))

zicxc 2004-09-11
  • 打赏
  • 举报
回复
select cast(cast(score as int)/5*5 as varchar(10))+'--'+cast((cast(score as int)/5+1)*5 as varchar(10)) as 分数段,
count(*) as 人数
from table1
group by cast(score as int)/5

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧