这个问题在这里已经有了答案:
SELECT every employee that has a higher salary than the AVERAGE of his department
(7 个回答)
7年前关闭。
我有一个名为员工的表,里面有姓名、部门 ID 和薪水。我想找到工资高于他们部门平均工资的员工,并查看他们的姓名,department_id,工资和他们部门的平均工资。我已经写了这段代码,但它不起作用。我们怎样才能解决这个问题?提前致谢。
SELECT name, department_id, salary, avg(salary)
FROM employees
GROUP BY name, department_id, salary
HAVING salary > (select avg(salary) from employees group by department_id)
我已经更新了我的代码,如您所说:
SELECT department_id, salary, avg(salary), count(*)
FROM employees e
GROUP BY department_id, salary
HAVING salary > (select avg(salary) from employees e2 where e2.department_id=e.department_id)
但是当我运行它时,我得到了这个结果:
你可以看到工资和平均值是一样的,有 2 个部门 80 年代,我需要所有现有部门中的 1 个。我们如何解决这个问题。如果这很重要,我正在使用 Oracle 数据库。谢谢。
最佳答案
您的代码非常接近。但是,而不是 group by
在子查询中,它需要与外部查询相关联。而且,您不需要外部聚合,只需一个 where
条款:
SELECT name, department_id, salary
FROM employees e
WHERE salary > (select avg(salary) from employees e2 where e2.department_id = e.department_id);
但是,您可能正在学习 Oracle。您还可以使用分析函数编写此查询:
select e.*
from (select e.*, avg(salary) over (partition by department) as avgsalary
from employees e
) e
where e.salary > e.avgsalary;
尽管这对于您正在学习的内容来说可能有点高级,但我鼓励您理解这两个查询。
关于sql - 工资高于部门平均水平的员工?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25229357/