我有一张名为“tblEmployee”的表。此表中的列为“EmpId”,“部门”,“薪酬”。 (e1,sales,10000),(e2,hr,20000),(e3,sales,30000),(e4,production,40000),(e5,hr,50000)。 我想检索工资大于各自部门平均工资的员工姓名。我想为sql server解决方案。如何检索薪水高于其各自部门平均工资的员工的姓名
在此先感谢。
我有一张名为“tblEmployee”的表。此表中的列为“EmpId”,“部门”,“薪酬”。 (e1,sales,10000),(e2,hr,20000),(e3,sales,30000),(e4,production,40000),(e5,hr,50000)。 我想检索工资大于各自部门平均工资的员工姓名。我想为sql server解决方案。如何检索薪水高于其各自部门平均工资的员工的姓名
在此先感谢。
select emp.EmpId, emp.Department
from tblEmployee emp
where emp.Salary > (select
avg(emp2.Salary)
from tblEmployee emp2
where emp2.Department = emp.Department
)
凡@department被传入的参数表示哪个部门?
select * from tblEmployee where Salary >
(select AVG(Salary) from tblEmployee where Department = @department)
and Department = @department
order by salary desc
通过使用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
+1正确的答案。虽然我只想做一个内联选择和内联接,因为CTE没有得到普遍支持。 –
@ liho1eye:true,但假设SQL Server 2005中都添加了CTE和OVER子句。 – gbn
这适用于我:
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
看看[group by](h TTP://msdn.microsoft.com/en-us/library/ms177673.aspx)。这将让您计算每个部门的平均薪资。然后,您可以简单地加入结果集,以查找薪水高于平均水平的员工。 –