使用group by从两个不同的表中求平均值

时间:2016-02-19 21:20:02

标签: group-by inner-join

我有一个名为DEPARTMENTS with table的表格: DepartmentID的 DepartmentName的

另一个名为EMPLOYEE的表格: 员工ID DepartmentID的 员工姓名 薪水

我需要一个带有Group By的JOIN查询来显示DepartmentName和AVERAGE Salary

基本上输出应显示: DepartmentX 40000 部门15000 DepartmmentZ 35000

1 个答案:

答案 0 :(得分:0)

您需要在两个表之间使用AVG()聚合函数和JOIN,例如

SELECT d.DepartmentName,
AVG(e.Salary) as average_salary
FROM Employee e 
JOIN DEPARTMENTS d ON e.DepartmentID = d.DepartmentID 
GROUP BY e.DepartmentID;

(OR)首先获得平均值,然后执行JOIN之类的

SELECT d.DepartmentName,
xx.average_salary
FROM DEPARTMENTS d 
JOIN (
select DepartmentID, AVG(Salary) as average_salary
from Employee 
GROUP BY DepartmentID) xx  ON xx.DepartmentID = d.DepartmentID;