前言
这几年一直在it行业里摸爬滚打,一路走来,不少总结了一些python行业里的高频面试,看到大部分初入行的新鲜血液,还在为各样的面试题答案或收录有各种困难问题
于是乎,我自己开发了一款面试宝典,希望能帮到大家,也希望有更多的Python新人真正加入从事到这个行业里,让python火不只是停留在广告上。
微信小程序搜索:Python面试宝典
或可关注原创个人博客:https://lienze.tech
也可关注微信公众号,不定时发送各类有趣猎奇的技术文章:Python编程学习
分组
SQL分组使用GROUP BY
语句
什么叫分组¿
可以将指定同类字段组合为一条,通过分组可以对其进行一系列聚合操作,比如获取每个老师的学生各有多少个
select teacher_id, count(teacher_id) from student
group by teacher_id
where teacher_id=3
比如现在表中有如下数据,学生们具有了分数
+----+------------------+------------+-------+
| id | name | teacher_id | score |
+----+------------------+------------+-------+
| 1 | 模拟小学生1 | 1 | 76 |
| 2 | 模拟小学生2 | 1 | 89 |
| 3 | 模拟小学生3 | 2 | 59 |
| 4 | 模拟初中生1 | 2 | 77 |
| 5 | 模拟初中生2 | 3 | 88 |
| 6 | 模拟初中生3 | 3 | 47 |
+----+------------------+------------+-------+
SUM
希望查询每个老师他所带领学生的总分数,可以结合SUM
函数
select Teacher.name, sum(score)
from Student
left join Teacher on Teacher.id = Student.teacher_id
group by teacher_id;
为了能够更好的体现结果,可以结合左连接将老师表关联,取到对应的老师名
由于还用了左连接,那么某些老师id对应老师数据为空的也会聚合起来,做一个统计
+-----------+------------+
| name | sum(score) |
+-----------+------------+
| 李老师 | 165 |
| 彭老师 | 136 |
| NULL | 135 |
+-----------+------------+
MAX
获取学生中属于老师们成绩最大的
select Teacher.name, max(score)
from Student
left join Teacher on Teacher.id = Student.teacher_id
group by teacher_id;
每个老师里最优秀的学生是谁呢?
+-----------+------------+
| name | max(score) |
+-----------+------------+
| 李老师 | 89 |
| 彭老师 | 77 |
| NULL | 88 |
+-----------+------------+
MIN
也可以获取到成绩最差的学生
select Teacher.name, min(score)
from Student
left join Teacher on Teacher.id = Student.teacher_id
group by teacher_id;
谁是最擦斤的学生呢¿
+-----------+------------+
| name | min(score) |
+-----------+------------+
| 李老师 | 76 |
| 彭老师 | 59 |
| NULL | 47 |
+-----------+------------+
COUNT
获取到老师们具有的所有学生数量
select Teacher.name, count(Teacher.id)
from Student
left join Teacher on Teacher.id = Student.teacher_id
group by teacher_id;
+-----------+-------------------+
| name | count(Teacher.id) |
+-----------+-------------------+
| 李老师 | 2 |
| 彭老师 | 2 |
| NULL | 0 |
+-----------+-------------------+
AVG
获取到老师们所带学生的平均成绩
select Teacher.name, avg(score) avg_score
from Student
left join Teacher on Teacher.id = Student.teacher_id
group by teacher_id
order by avg_score desc
看看哪些老师所带的学生平均质量比较好
+-----------+-----------+
| name | avg_score |
+-----------+-----------+
| 李老师 | 82.5000 |
| 彭老师 | 68.0000 |
| NULL | 67.5000 |
+-----------+-----------+