如何检索工资大于其各自部门平均工资的员工姓名

时间:2011-12-06 14:01:23

标签: sql-server

我有一个名为“tblEmployee”的表。此表中的列是“EmpId”,“Department”,“Salary”。 该表中的行如下(e1,销售额,10000),(e2,hr,20000),(e3,销售额,30000),(e4,生产,40000),(e5,hr,50000)。 我想检索薪水大于各自部门平均工资的员工的姓名。我想要sql server的解决方案。

提前致谢。

4 个答案:

答案 0 :(得分:4)

select emp.EmpId, emp.Department
  from tblEmployee emp
  where emp.Salary > ( select
                           avg(emp2.Salary)
                         from tblEmployee emp2
                         where emp2.Department = emp.Department
                     )

答案 1 :(得分:1)

通过使用OVER子句生成内联AVG来避免聚合

;WITH cte as
(
    select
       EmpId, Department, Salary,
       AVG(Salary) OVER (PARTITION BY Department) AS DeptAvgSal
    FROM
       tblEmployee
)
SELECT
   EmpId, Department, Salary
FROM
   cte
WHERE
   Salary > DeptAvgSal

答案 2 :(得分:1)

这对我有用:

select e.eid,e.did,e.ename,e.sal,t.avg_sal dpt_avg_sal from emp e inner join
(select emp.did, AVG(sal) avg_sal from emp inner join dpt on emp.did = dpt.did
group by emp.did) t
on  e.did = t.did where e.sal > avg_sal

答案 3 :(得分:0)

其中@department是传入的参数,表示哪个部门......

select * from tblEmployee where Salary > 
  (select AVG(Salary) from tblEmployee where Department = @department)
and Department = @department
order by salary desc