LeetCode:Database 43.项目员工II

Posted Xiao Miao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 43.项目员工II相关的知识,希望对你有一定的参考价值。

要求:编写一个SQL查询,报告所有雇员最多的项目。

Project 表的结构:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| project_id  | int     |
| employee_id | int     |
+-------------+---------+
主键为 (project_id, employee_id)。
employee_id 是员工表 Employee 表的外键。

Employee 表的结构:

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| employee_id      | int     |
| name             | varchar |
| experience_years | int     |
+------------------+---------+
主键是 employee_id。

Project 表:

+-------------+-------------+
| project_id  | employee_id |
+-------------+-------------+
| 1           | 1           |
| 1           | 2           |
| 1           | 3           |
| 2           | 1           |
| 2           | 4           |
+-------------+-------------+

Employee 表:

+-------------+--------+------------------+
| employee_id | name   | experience_years |
+-------------+--------+------------------+
| 1           | Khaled | 3                |
| 2           | Ali    | 2                |
| 3           | John   | 1                |
| 4           | Doe    | 2                |
+-------------+--------+------------------+

Result table:

+-------------+
| project_id  |
+-------------+
| 1           |
+-------------+

分析:
1.查询雇员最多的项目,因此需要以项目id进行分组,取得每个项目总人数
2.对人数进行降序排序,取得人数最多的项目,可能存在人数相同的项目,因此使用rank() over()函数取得并列的项目
3.取得序号等于1的结果即为最终结果

SQL语句:

#1.方法1
select p as project_id from(
select p,rank() over(order by c desc) as r from
(
select project_id as p,count(*) as c
from project
group by project_id
)a
)b
where r=1;
#2.方法2
select project_id from
project 
group by project_id
having count(*)=
(select count(*) as c from project group by project_id order by c desc limit 1 );

以上是关于LeetCode:Database 43.项目员工II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:Database 44.项目员工 III

LeetCode:Database 17.员工奖金

LeetCode:Database 13.员工薪水中位数

LeetCode:Database 90.使用唯一标识码替换员工ID

LeetCode:Database 79.求团队人数

LeetCode:Database 75.向公司CEO汇报工作的所有人