我需要找到每个部门的最高平均工资。然后,我只需要返回具有最高平均薪水且保留两位小数的部门(NAME和DEPT_MAX_AVG_SALARY)(即,可能有多个具有相同的最高平均薪水的小数,这很好,我们需要所有相等的部门该金额)。
SELECT p.DEPARTMENT_ID, d.NAME, cast(AVG(p.SALARY) as decimal(18,2)) as AVERAGE
FROM PROFESSOR p
INNER JOIN DEPARTMENT d ON p.DEPARTMENT_ID = d.ID
GROUP BY p.DEPARTMENT_ID, d.NAME
HAVING AVG(p.SALARY) =
(
SELECT TOP 1 AVG(a.SALARY) as MAXAVERAGE
FROM PROFESSOR a
INNER JOIN DEPARTMENT b
ON a.DEPARTMENT_ID = b.ID
GROUP BY a.DEPARTMENT_ID
ORDER BY MAXAVERAGE DESC
)
ORDER BY AVERAGE DESC
有更好的方法吗?
答案 0 :(得分:0)
select max(d.avg) from (
select avg(salary) "avg" from professor group by department
) as d
这显然是简化版本,但是逻辑在那里。您从派生表中计算出的平均值中选择最大值,该平均值按部门分组。
答案 1 :(得分:0)
我建议您尝试使用WITH TIES
和ORDER BY
:
Select TOP 1 WITH TIES
d.NAME as dep_name
,AVG(cast(p.SALARY as decimal(18,2)) as avg_dep_salary
From PROFESSOR p
Inner join DEPARTMENT d on p.DEPARTMENT_ID = d.ID
Group by
d.ID
,d.NAME
Order by avg_dep_salary desc
答案 2 :(得分:0)
TOP (1) WITH TIES
是必经之路。但是我认为查询看起来像这样:
select top (1) with ties d.id, d.NAME as dep_name,
cast(avg(p.SALARY) as decimal(18, 2)) as avg_dep_salary
from PROFESSOR p Inner join
DEPARTMENT d
on p.DEPARTMENT_ID = d.ID
group by d.ID, d.NAME
order by avg_dep_salary desc;
在计算平均值之后,强制转换值 很重要。如果salary
是整数,那么您可能需要:
cast(avg(p.SALARY * 1.0) as decimal(18, 2)) as avg_dep_salary