标签:dep count select manager rtm -- 结果 book 题目
编写一个 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
在 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
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
标签:dep count select manager rtm -- 结果 book 题目
原文地址:https://www.cnblogs.com/coding-gaga/p/12940482.html