选择薪水高于其部门平均薪水的每位员工

时间:2013-11-26 05:46:18

标签: mysql sql

我的数据库中只有一个名为 EMPLOYEE 的表,其中包含以下3个列:

Employee_Name, Employee_Salary, Department_ID

现在我必须选择薪水高于其部门AVERAGE的每位员工。 我该怎么做?

我遇到的主要问题是将每个Employee_Salary与

进行比较
SELECT  AVG(department_ID) FROM employee GROUP BY Department_ID

内部队列的返回集返回多行。

我想我需要执行连接操作,但我不知道如何。

7 个答案:

答案 0 :(得分:3)

请尝试以下查询

Select * from employee a where Employee_Salary > (select avg(Employee_Salary) from 
employee b group by Department_ID having b.Department_ID = a.Department_ID)

Select * from employee a where Employee_Salary> (select avg(Employee_Salary) from 
employee b where b.Department_ID = a.Department_ID group by Department_ID)

答案 1 :(得分:1)

假设Postgres,

试试这个

select e1.* from emp e1  inner join (select avg(sal) avg_sal,dept_id from emp group by dept_id) as e2 on e1.dept_id=e2.dept_id and e1.sal>e2.avg_sal

答案 2 :(得分:0)

试试这个......这没有经过测试。

SELECT * from employee join (SELECT AVG(employee_salary) as sal, department_ID 
FROM employee GROUP BY Department_ID) as t1 
ON employee.department_ID = t1.department_ID 
where employee.employee_salary > t1.sal

答案 3 :(得分:0)

不使用GROUP BY

尝试此操作
SELECT * FROM employee  E1 
WHERE [Employee_Salary] > (
                            SELECT AVG([Employee_Salary]) FROM employee  E2 
                            WHERE E2.[Department_ID] = E1.[Department_ID]
                           )

SQL FIDDLE DEMO

答案 4 :(得分:0)

尝试使用EXISTS()之类的:

SELECT t1.Employee_Name, t1.Employee_Salary, t1.Department_ID
FROM Employee t1
WHERE EXISTS
(
 SELECT t2.Department_ID, AVG(t2.Employee_Salary) as AvgSalary
 FROM Employee t2
 WHERE   t1.Department_ID = t2.Department_ID
 GROUP BY t2.Department_ID
 HAVING t1.Employee_Salary>AVG(t2.Employee_Salary)

);

请参阅Fiddle Demo

答案 5 :(得分:0)

你也可以尝试这种方式!

  select FirstName,E.DepartmentName,BaseRate,EB.avgSAL
  From DimEmployee E
  inner join
  (select avg(BaseRate) As avgSAL,DepartmentName
  from DimEmployee
  group by DepartmentName ) EB
  ON E.DepartmentName = Eb.DepartmentName
  where E.BaseRate > Eb.avgSAL

答案 6 :(得分:-1)

也尝试以下操作:

Select e.ename, e.sal, e.deptno
from (select e.*, avg(sal) over (partition by deptno) as avgsalary
      from EMP_TABLE e
     ) e
where e.sal > e.avgsalary;