题目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

最新文章

  1. C语言语法分析器
  2. appium 常用API
  3. 神奇的Bank系统之旅哦
  4. Jquery 实现input回车时跳转到下一个input元素
  5. 【动态规划】The Triangle
  6. 仿iOS底部弹出popUpWindow
  7. Spring-接口调用
  8. @(报错)could not find the main class, Program will exit(已解决)
  9. SAC E#1 - 一道神题 Sequence1
  10. package.json 中script脚本传入参数问题
  11. (二)文档请求不同源之location.hash跨域
  12. 如何对MongoDB 3.2.7进行用户权限管理配置
  13. ASP.NET学习笔记(1)
  14. eval & sleep
  15. tensorflow 导入新的tensorflow实例
  16. 2017, X Samara Regional Intercollegiate Programming Contest 题解
  17. [django]form不清空问题解决
  18. 本地搭建https服务
  19. 如何让自己的广播只让指定的 app 接收?
  20. 021.8 properties(开发使用频率高)

热门文章

  1. 坚持第一天:HashMap和Hashtable的区别
  2. 带你用 Python 实现自动化群控设备
  3. C#分布式登录——jwt
  4. exe调用DLL的方式
  5. XSS的构造技巧
  6. centos iso镜像自动挂载
  7. 【转】Windows10删除文件时却提示文件不存在的解决方案
  8. oracle练习前期准备
  9. 力扣Leetcode 983. 最低票价
  10. JS 替换日期的横杠为斜杠