# mysql中位数、众数计算

s_id 为学生id
c_id 为课程id
s_score 为课程成绩

1、中位数

``````mysql> select s_score from score where c_id='02';
+---------+
| s_score |
+---------+
|      90 |
|      60 |
|      80 |
|      30 |
|      87 |
|      89 |
+---------+
6 rows in set (0.00 sec)
``````

``````mysql> select avg(c.s_score) from(
->   select a.s_score from score a,score b
->   where a.c_id=b.c_id and a.c_id='02'
->   group by a.s_score
->   having sum(case when a.s_score=b.s_score then 1 else 0 end)
->          >= abs(sum(sign(a.s_score-b.s_score)))
->   )c;
+----------------+
| avg(c.s_score) |
+----------------+
|        83.5000 |
+----------------+
1 row in set (0.00 sec)
``````

``````mysql> select a.s_score,
-> sum(case when a.s_score=b.s_score then 1 else 0 end )as if_equal,
-> abs(sum(sign(a.s_score-b.s_score)))
-> from score a,score b where a.c_id=b.c_id and a.c_id='02'
-> group by a.s_score;
+---------+----------+-------------------------------------+
| s_score | if_equal | abs(sum(sign(a.s_score-b.s_score))) |
+---------+----------+-------------------------------------+
|      30 |        1 |                                   5 |
|      60 |        1 |                                   3 |
|      80 |        1 |                                   1 |
|      87 |        1 |                                   1 |
|      89 |        1 |                                   3 |
|      90 |        1 |                                   5 |
+---------+----------+-------------------------------------+
6 rows in set (0.00 sec)
``````

2、众数

``````mysql> select s_score from score where c_id='02';
+---------+
| s_score |
+---------+
|      90 |
|      60 |
|      80 |
|      30 |
|      80 |
|      89 |
+---------+
6 rows in set (0.00 sec)

mysql> select s_score from score
-> where c_id='02'
-> group by s_score
-> having count(*)
->        >= all(select count(*) from score where c_id='02' group by s_score);
+---------+
| s_score |
+---------+
|      80 |
+---------+
1 row in set (0.00 sec)
``````

``````mysql> select s_score,count(*) from score where c_id='02' group by s_score;
+---------+----------+
| s_score | count(*) |
+---------+----------+
|      30 |        1 |
|      60 |        1 |
|      80 |        2 |
|      89 |        1 |
|      90 |        1 |
+---------+----------+
5 rows in set (0.00 sec)
``````

count() >= all(select count() from score where c_id=’02’ group by s_score)

原文作者：Taodede
原文地址: https://www.jianshu.com/p/bd63f5b64a27
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。