如何在每个部门显示department_id,job_id和每个职位分类的平均工资?

时间:2016-04-29 09:29:12

标签: sql group-by subquery correlated-subquery

我试过这个但显然它只会给所有部门的平均工资而不是每个工作分类

SELECT e.department_id, e.job_id, (SELECT avg(salary)
                                   FROM employees)
FROM employees e
GROUP BY department_id, job_id;

2 个答案:

答案 0 :(得分:2)

你想要部门的平均薪水吗?做一个相关的子查询:

SELECT e.department_id, e.job_id, (SELECT avg(salary)
                                   FROM employees e2
                                   where e2.department_id = e.department_id)
FROM employees e

答案 1 :(得分:1)

我想你想要这个(如果你的目标是得到几个department_id / job_id的平均工资):

SELECT e.department_id, e.job_id, avg(e.salary)
FROM employees e
GROUP BY e.department_id, e.job_id;

如果你只想要department_id的平均值,你可以写:

SELECT e.department_id, e.job_id, 
    (SELECT avg(e1.salary)
    FROM employees e1
    where e1.department_id = e.department_id)
FROM employees e
GROUP BY e.department_id, e.job_id;