有两个表
Employee
Id
Name
Salary
DepartmentId
和
Departament
Id
Name
我如何在两张桌子中获得最高的平均工资 喜欢
Joe and Max belong to dept 1 so, avg is (70K+90K)/2
= 80K
和
Henry and Sam belog to dept 2, avg is (80K + 60K)/2=70k
那么在这种情况下,如何通过depto选择最高的平均工资?
IT 80K
我一直在尝试:
'将每个部门的工资分组,并使用“最高”功能获得最高的工资。
select
Department.Name as Department,
T.M as Salary
from
Employee,
Department,
(select DepartmentId as ID, Max(Salary) as M from Employee group by DepartmentId) as T
where
Employee.Salary = T.M and
Department.Id = T.ID and
Employee.DepartmentId = Department.Id
答案 0 :(得分:0)
如果只想获取部门的平均值,则可以使用这种方式。
select DepartmentId as ID, de.name as Deptname, Avg(Salary) as M from Employee em1
join Department de on de.departmentID = em1.DepartmentId
group by DepartmentId, de.name
如果您希望员工姓名与最高平均水平一起使用,则也可以使用此方法。
select
Deptname as Department,
e.Name as Employeename,
z.M as Salary
from
Employee e
join
( select DepartmentId,Deptname, M, row_number() (order by m desc) rownum from ( select DepartmentId as ID, de.name as Deptname, Avg(Salary) as M from Employee em1
join Department de on de.departmentID = em1.DepartmentId
group by DepartmentId, de.name) as T) z
on
e.DepartmentId = T.DepartmentId and z.rownum = 1
答案 1 :(得分:0)
如果您想获得完整的答案,则应提供DDL,样本数据和所需的结果。 如果我对您的理解正确,那么您正在寻找以下内容:
SELECT DepartmentID, AVG(Salary) AS AverageSalaryForDept
FROM Employee
GROUP BY DepartmentID
ORDER BY AverageSalaryForDept DESC;
这将给您所有平均值,从最高到最低排序。现在,如果您只想要最上面的一个,请添加一个FETCH子句:
SELECT DepartmentID, AVG(Salary) AS AverageSalaryForDept
FROM Employee
GROUP BY DepartmentID
ORDER BY AverageSalaryForDept DESC
OFFSET 0 ROWS FETCH NEXT 1 ROW ONLY;
HTH
答案 2 :(得分:0)
如果多个部门的平均平均工资相同,则此解决方案将返回多行。
SELECT *
FROM(
SELECT d.Id, d.Name, AVG(e.Salary) avg_salary, RANK() OVER(ORDER BY AVG(e.Salary) DESC) AS rank_
FROM Employee e
INNER JOIN Departament d ON e.DepartmentId = d.Id
GROUP BY d.Id, d.Name
)T
WHERE rank_ = 1