[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

posted on   coding_gaga  阅读(199)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
阅读排行:
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· .NET Core奇技淫巧之WinForm使用Python.NET并打包
· Java24你发任你发,我用Java8
· C# 中比较实用的关键字,基础高频面试题!
历史上的今天:
2019-05-22 [程序员代码面试指南]数组和矩阵问题-数组中子数组的最大累乘积
2019-05-22 [算法题]最小m划分(划分DP)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示