SQL查询——同一张表的横向与纵向同时比较

表名:student

表结构及数据

+----+--------+---------+------+------------+--------------+---------+
| 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 |
+----+--------+---------+------+------------+--------------+---------+

 

需求:在该表中查出最偏科的学生姓名。

 

分析

这张表中有三个科目:English、math、Chinese

1-求出三个科目的分数差(求绝对值)——使用abs(math-english)      abs(chinese-english)       abs(math-chinese)

2-求出整个班级中        数学与英语的分数差、语文与英语的分数差、数学与英语的分数差          的最大值——max(abs(math-english) )、    max(abs(chinese-english)) 、    max(abs(math-chinese))

3-在2的结果中查找出数值最大的值

4-在student表中搜索                 

                      数学与英语的分数差     等于    (3-的结果)      

                      语文与英语的分数差     等于    (3-的结果)

                      数学与英语的分数差      等于    (3-的结果)

如此可以查找出最偏科的学生姓名。

 

 

SQL代码

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);

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。