我有一張名爲「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)。這將讓您計算每個部門的平均薪資。然後,您可以簡單地加入結果集,以查找薪水高於平均水平的員工。 –