如何使用avg()加入两个结果?

时间:2015-03-05 08:30:22

标签: sql

我有两个查询结果:

Select avg(salary), department_id 
from employees
Group by department_id

Select d.department_name, e.department_id
From departments d, employees e
Where e.department_id=d.department_id

如何将结果合并为一个结果。部门ID首先是两个表的主键

我尝试了联盟,创造了新的表......没有什么可行的我需要这样的东西:

Dept_id  |  Dept_name  |  avg_salary  |
---------------------------------------
121      |  Management |   324000     |
---------------------------------------
102      |  Tax        |    432555    |
---------------------------------------
Etc

1 个答案:

答案 0 :(得分:2)

我假设您希望每个部门都avarage salary。为此,您应将JOINgroup by一起使用。 AVG汇总以获得部门的平均工资。试试这个,

SELECT 
    d.department_id,
    d.department_name,
    AVG(e.Salary) AS avarageSalary
FROM
   Department d JOIN Employee e
      ON d.department_id= e.department_id
GROUP BY
    d.department_id,d.department_name