SELECT every employee that has a higher salary than the AVERAGE of his department

后端 未结 7 1341
臣服心动
臣服心动 2021-01-13 23:46

I have only 1 table named EMPLOYEE on my database with the 3 following collumns:

Employee_Name, Employee_Salary, Department_ID
相关标签:
7条回答
  • 2021-01-14 00:23

    Try using EXISTS() like:

    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)
    

    );

    See Fiddle Demo

    0 讨论(0)
  • 2021-01-14 00:25

    Assuming Postgres,

    Try This

    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
    
    0 讨论(0)
  • 2021-01-14 00:31

    please try with below query

    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)
    

    or

    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)
    
    0 讨论(0)
  • 2021-01-14 00:35

    Try This... This not tested.

    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
    
    0 讨论(0)
  • 2021-01-14 00:38

    you can try this way as well !

      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
    
    0 讨论(0)
  • 2021-01-14 00:43

    Try this without 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

    0 讨论(0)
提交回复
热议问题