1、题目描述
Write an SQL query that reports all the projects that have the most employees.
The query result format is in the following example:
Project table:
project_id | employee_id |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 1 |
2 | 4 |
Employee table:
employee_id | name | experience_years |
---|---|---|
1 | Khaled | 3 |
2 | Ali | 2 |
3 | John | 1 |
4 | Doe | 2 |
Result table:
project_id |
---|
1 |
The first project has 3 employees while the second one has 2.
来源:力扣(LeetCode)
2、解题思路
1# 主要是解决,出现多个最大值的情况
2# 首先增加子表,使用倒序和限制数量组合,得出最大值group by project_id order by count(employee_id) desc limit 1
select count(employee_id)
from Project
group by project_id
order by count(employee_id) desc
limit 1
3# 然后,直接让count(employee_id)
等于上述值就行了
3、提交记录
select project_id
from Project
group by project_id
having count(employee_id)=
(select count(employee_id)
from Project
group by project_id
order by count(employee_id) desc
limit 1 )