LeetCode刷题-数据库(MySQL)-1075. Project Employees I

1075. Project Employees I

一、题目描述

Table: Project

Column Name Type
project_id int
employee_id int

(project_id, employee_id) is the primary key of this table.
employee_id is a foreign key to Employee table.

Table: Employee

Column Name Type
employee_id int
name varchar
experience_years int

employee_id is the primary key of this table.

Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.

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 average_years
1 2.00
2 2.50

The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/project-employees-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

求每一个项目(project_id)所雇佣工人(employee_id)的平均工作年限(experience_years)。
本题有三点需要注意:

  1. 首先,注意到project_id与experience_years分属于两个表,所以需要对两个表进行连接。因表Project的主键为(project_id, employee_id),所以两个列均无空值,直接使用内连接即可。
  2. 对project_id使用GROUP BY,然后对experience_years使用AVG()函数求平均值。
  3. 题目中要求保留2位小数,使用ROUND()函数即可。

三、代码实现

SELECT
	p.project_id,
	ROUND(AVG(e.experience_years), 2) AS average_years
FROM
	Project p
JOIN
	Employee e
ON p.employee_id = e.employee_id
GROUP BY project_id;

注:该题目的leetcode测试用例应该是有问题,总是出现执行错误。

你可能感兴趣的:(MySQL)