sql 分组求中位数

InsistOnDoing 2009-05-19 09:07:45
表score,拥有字段sid(学号),cid(课程号),分数(score)
sid cid score
1 1 88
2 1 92
3 1 88
1 2 98
2 2 98
3 2 78
4 2 90
根据课程号得到每门课程的中位数
结果如图所示:
cid score
1 88
2 94
...全文
702 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
InsistOnDoing 2009-05-20
  • 打赏
  • 举报
回复
结贴了,见者有分啊
InsistOnDoing 2009-05-20
  • 打赏
  • 举报
回复
谢谢大家的支持,haiwer已经帮我解决了。
昵称被占用了 2009-05-20
  • 打赏
  • 举报
回复
declare @score table (
sid int,
cid int,
score int
)
insert @score select
1, 1, 88
union all select
2, 1, 92
union all select
3, 1, 88
union all select
1, 2, 98
union all select
2, 2, 98
union all select
3, 2, 78
union all select
4, 2, 90


select c.cid,avg(r.score) as score
from (
select * ,(select count(1) from @score where cid=a.cid and (score<a.score or score=a.score and sid<=a.sid)) as Num
from @score a
) as r,(select cid,count(1) as cnt from @score group by cid) as c
where r.cid=c.cid
and (c.cnt % 2 = 0
and (r.num = c.cnt / 2
or r.num = c.cnt / 2 +1)
or c.cnt % 2 = 1
and r.num = (c.cnt+1) / 2
)
group by c.cid

--结果
cid score
----------- -----------
1 88
2 94

(2 行受影响)
InsistOnDoing 2009-05-19
  • 打赏
  • 举报
回复
刚开始的时候我想写个试图,发现能力不足。
如果能用存储过程也行。
InsistOnDoing 2009-05-19
  • 打赏
  • 举报
回复
中位数通俗的讲就是处于中间位置的数,对于基数个数,例如1,2,3,4,5,一共有5个数,处于中间的是第3个数也就是3。
而对于偶数个数,例如1,2,2,3,3,4就是第3和第4个数的平均,也就是(2+3)/2=2.5
中位数的基础是数据需要排序
--小F-- 2009-05-19
  • 打赏
  • 举报
回复
这个还要分2种情况
liping_ycit 2009-05-19
  • 打赏
  • 举报
回复
中位数是啥,平均分?
--小F-- 2009-05-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 josy 的回复:]
什么叫“中位数”?
[/Quote]
  中位数(Median)统计学名词。
  将数据排序后,位置在最中间的数值。即将数据分成两部分,一部分大于该数值,一部分小于该数值。中位数的位置:当样本数为奇数时,中位数=(N+1)/2 ; 当样本数为偶数时,中位数为N/2与1+N/2的均值 ,或求出中间两个数的平均数作为中位数。
百年树人 2009-05-19
  • 打赏
  • 举报
回复
什么叫“中位数”?

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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