[LeetCode]Mysql系列5
题目1 1112. 每位学生的最高成绩
编写一个 SQL 查询,查询每位学生获得的最高成绩和它所对应的科目,若科目成绩并列,取 course_id 最小的一门。查询结果需按 student_id 增序进行排序。
题解
注意这里grade的外层查询需要结合group by,或者查max(grade),或者使用join查grade
代码
# Write your MySQL query statement below
select student_id, min(course_id) as course_id,grade
from Enrollments
where (student_id,grade) in(
select student_id,max(grade) as grade
from Enrollments
group by student_id
)
group by student_id,grade
order by student_id
题目2 614. 二级关注者
在 facebook 中,表 follow 会有 2 个字段: followee, follower ,分别表示被关注者和关注者。
请写一个 sql 查询语句,对每一个关注者,查询关注他的关注者的数目。
比方说:
+-------------+------------+
| followee | follower |
+-------------+------------+
| A | B |
| B | C |
| B | D |
| D | E |
+-------------+------------+
应该输出:
+-------------+------------+
| follower | num |
+-------------+------------+
| B | 2 |
| D | 1 |
+-------------+------------+
解释:
B 和 D 都在在 follower 字段中出现,作为被关注者,B 被 C 和 D 关注,D 被 E 关注。A 不在 follower 字段内,所以A不在输出列表中。
题解
当新的字段名和原表的其他字段名一样时,可以原表.原字段 这样来与新别名区分。
代码
# Write your MySQL query statement below
select f.followee as follower,count(distinct f.follower) as num
from follow f
where followee in(
select distinct follower
from follow
)
group by f.followee
题目3 570. 至少有5名直接下属的经理
Employee 表包含所有员工和他们的经理。每个员工都有一个 Id,并且还有一列是经理的 Id。
+------+----------+-----------+----------+
|Id |Name |Department |ManagerId |
+------+----------+-----------+----------+
|101 |John |A |null |
|102 |Dan |A |101 |
|103 |James |A |101 |
|104 |Amy |A |101 |
|105 |Anne |A |101 |
|106 |Ron |B |101 |
+------+----------+-----------+----------+
给定 Employee 表,请编写一个SQL查询来查找至少有5名直接下属的经理。对于上表,您的SQL查询应该返回:
+-------+
| Name |
+-------+
| John |
+-------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/managers-with-at-least-5-direct-reports
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
首先考虑join,再考虑where子查询,一些情景两者都可实现。
代码
# Write your MySQL query statement below
select Name
from Employee
join(
select ManagerId
from Employee
where ManagerId is not null
group by ManagerId
having count(ManagerId) >= 5
) tmp1
on Employee.Id = tmp1.ManagerId
最新文章
- C语言语法分析器
- appium 常用API
- 神奇的Bank系统之旅哦
- Jquery 实现input回车时跳转到下一个input元素
- 【动态规划】The Triangle
- 仿iOS底部弹出popUpWindow
- Spring-接口调用
- @(报错)could not find the main class, Program will exit(已解决)
- SAC E#1 - 一道神题 Sequence1
- package.json 中script脚本传入参数问题
- (二)文档请求不同源之location.hash跨域
- 如何对MongoDB 3.2.7进行用户权限管理配置
- ASP.NET学习笔记(1)
- eval &; sleep
- tensorflow 导入新的tensorflow实例
- 2017, X Samara Regional Intercollegiate Programming Contest 题解
- [django]form不清空问题解决
- 本地搭建https服务
- 如何让自己的广播只让指定的 app 接收?
- 021.8 properties(开发使用频率高)