注册 登录
编程论坛 MySQL论坛

SQL如何查询出最偏科的学生信息

ithaibo 发布于 2015-04-30 21:13, 2976 次点击
如题,一张表:
+----+--------+---------+------+------------+--------------+---------+
| id | name   | english | math | birthday   | native_place | chinese |
+----+--------+---------+------+------------+--------------+---------+
|  1 | 潘怡茹 |      86 |   91 | 1990-01-01 | 上海         |      97 |
|  2 | 刘濮松 |      88 |   68 | 1990-02-01 | 上海         |      96 |
|  3 | 刘吉如 |      85 |   53 | 1990-03-01 | 上海         |      70 |
|  4 | 李岩珂 |      85 |   70 | 1990-04-01 | 上海         |      96 |
|  5 | 王晓博 |      85 |   79 | 1990-05-01 | 上海         |      46 |
|  6 | 李帅旭 |      79 |   76 | 1990-06-01 | 上海         |      97 |
|  7 | 李静瑶 |      89 |   61 | 1990-07-01 | 上海         |      92 |
|  8 | 金纾凡 |      80 |   43 | 1990-08-01 | 上海         |      83 |
|  9 | 秦梓航 |      57 |   46 | 1990-09-01 | 上海         |      86 |
| 10 | 关颖利 |      80 |   77 | 1991-01-01 | 上海         |      84 |
+----+--------+---------+------+------------+--------------+---------+

问题:如何找出最偏科的学生姓名?
5 回复
#2
ithaibo2015-05-02 16:40
select name from student
    where
        abs(chinese-math) in (select max(tmp.score)
                                from (
                                          select max(abs(s1.chinese-s1.math)) score from student s1
                                    union select max(abs(s2.chinese-s2.english)) score from student s2
                                    union select max(abs(s3.english-s3.math)) score from student s3
                                    ) tmp)
    or   
        abs(chinese-english)in (select max(tmp1.score)
                                from (
                                          select max(abs(s1.chinese-s1.math)) score from student s1
                                    union select max(abs(s2.chinese-s2.english)) score from student s2
                                    union select max(abs(s3.english-s3.math)) score from student s3
                                    ) tmp1)
    or   
        abs(english-math) in (select max(tmp2.score)
                                from (
                                          select max(abs(s1.chinese-s1.math)) score from student s1
                                    union select max(abs(s2.chinese-s2.english)) score from student s2
                                    union select max(abs(s3.english-s3.math)) score from student s3
                                    ) tmp2);
#3
ithaibo2015-05-02 16:40
结果为:
+--------+
| name   |
+--------+
| 金纾凡 |
| 秦梓航 |
+--------+
#4
ithaibo2015-05-02 16:41
如有优化方案,请指教!
#5
donaldlo2015-08-19 12:12
如果只是要找出任意两科差异最大的学生
select * from (
select id,name,max(math,english,cheese)-min(math,english,cheese) score1 from score)
order by score1 descending
#6
诸葛欧阳2015-10-16 09:38
楼上更简洁
1