MYSQL查询的逆向思维

+------+---------+-------+
| name | subject | socre |
+------+---------+-------+
| 张三 | 数学    |    90 |
| 张三 | 语文    |    50 |
| 张三 | 地理    |    40 |
| 李四 | 语文    |    55 |
| 李四 | 政治    |    45 |
| 王五 | 政治    |    30 |
+------+---------+-------+

找出不及格科目大于等于2的学生的总平均分

最好的方法是逆向查询,否则会用到子查询之类比较繁琐的检索语句

1,我们先找出所有学生的总平均分mysql> select name,avg(socre)
    -> from result
    -> group by name;
+------+------------+
| name | avg(socre) |
+------+------------+
| 张三 |    60.0000 |
| 李四 |    50.0000 |
| 王五 |    30.0000 |
+------+------------+

2,之后找出所有学生中每个学生的不及格科目的数量

mysql> select name,avg(socre),sum(socre<60)
    -> from result
    -> group by name;
+------+------------+---------------+
| name | avg(socre) | sum(socre<60) |
+------+------------+---------------+
| 张三 |    60.0000 |             2 |
| 李四 |    50.0000 |             2 |
| 王五 |    30.0000 |             1 |
+------+------------+---------------+

3,再找出不及格数目大于等于2的学生

mysql> select name,avg(socre),sum(socre<60)
    -> from result
    -> group by name
    -> having sum(socre<60)>=2;
+------+------------+---------------+
| name | avg(socre) | sum(socre<60) |
+------+------------+---------------+
| 张三 |    60.0000 |             2 |
| 李四 |    50.0000 |             2 |
+------+------------+---------------+

大功告成

猜你喜欢

转载自blog.csdn.net/weixin_42557907/article/details/81271333
今日推荐