Leetcode1076.项目员工分析II(简单)

题目
Table: Project

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| project_id  | int     |
| employee_id | int     |
+-------------+---------+

主键为 (project_id, employee_id)。
employee_id 是员工表 Employee 表的外键。

Table: Employee

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| employee_id      | int     |
| name             | varchar |
| experience_years | int     |
+------------------+---------+

主键是 employee_id。

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

查询结果格式如下所示:

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           |
+-------------+

第一个项目有3名员工,第二个项目有2名员工。

生成数据

CREATE TABLE Project(
project_id INT,
employee_id INT,
PRIMARY KEY(project_id, employee_id));

INSERT INTO Project VALUE(1,1),(1,2),(1,3),(2,1),(2,4);

解答
直接在Project 对 Project_id 分组 统计 employee_id 的数量 排序 取第一个即可

SELECT project_id
FROM Project
GROUP BY project_id
ORDER BY COUNT(*) DESC
LIMIT 0, 1;

对于这个例子是没有问题的 但是有一个问题就是 如果是有两个项目有三个员工且都是最多的呢 这个代码就有问题了
所以我们可以先选出项目最多的员工数再与各个部门的员工数进行连接

上面的代码改一下就可以得到最多的员工数

SELECT COUNT(*) as cnt
FROM Project
GROUP BY project_id
ORDER BY COUNT(*) DESC
LIMIT 0, 1;

然后再和各个部门进行匹配

SELECT project_id
FROM Project AS P
GROUP BY project_id
HAVING COUNT(P.`employee_id`) = (SELECT COUNT(*) AS cnt
FROM Project
GROUP BY project_id
ORDER BY COUNT(*) DESC
LIMIT 0, 1);

写的时候用的是where 一直在报错
一定要注意 基于分组的筛选条件要用 having

你可能感兴趣的:(Leetcode1076.项目员工分析II(简单))