SQL - 获取MAX AVG

时间:2017-11-20 17:56:01

标签: sql sql-server

所以我一直试图解决这个问题,尽管我在这里找到了许多有趣的东西,但我根本无法按照它的要求解决它。

我有两张桌子:

PROFESSOR (ID, NAME, DEPARTMENT_ID and SALARY) and
DEPARTMENT (ID, NAME).

我必须编写一个查询,显示具有最高平均SALARY的DEPARTMENT NAME。此外,如果多个部门的平均SALARY值最高,则应按任何顺序列出所有部门。

我尝试了很多东西,最后我创造了一个怪物,我想。我尝试使用HAVING,但它不像我那样工作。我输了。问题是我需要用来聚合函数。

SELECT b.nam, b.average
FROM ( SELECT DEPARTMENT.NAME AS nam, AVG(PROFESSOR.SALARY) AS average
   FROM PROFESSOR JOIN DEPARTMENT ON (PROFESSOR.DEPARTMENT_ID = 
DEPARTMENT.ID)
   GROUP BY DEPARTMENT.NAME) AS b
GROUP BY b.nam, b.average
ORDER BY b.average DESC

但是这个查询给我带来了所有部门的平均值,而不是最高值。

如果有人可以帮助我并以简单的方式解释我会非常感激。 谢谢!

4 个答案:

答案 0 :(得分:2)

你可以用它。如果多行具有相同的最大平均值,使用WITH TIES可以带来所有这些。

SELECT TOP 1 WITH TIES DEPARTMENT.NAME AS nam, AVG(PROFESSOR.SALARY) AS average
FROM PROFESSOR 
JOIN DEPARTMENT ON (PROFESSOR.DEPARTMENT_ID = DEPARTMENT.ID)
GROUP BY DEPARTMENT.NAME
ORDER BY AVG(PROFESSOR.SALARY) DESC

答案 1 :(得分:2)

;WITH x AS (

        SELECT t.dept,
               T.avg_sal,
               rank() OVER(ORDER BY t.avg_sal DESC) AS rnk

        FROM
           (
                SELECT d.name AS 'dept',
                       avg(p.salary) AS avg_sal
                FROM department AS d
                     INNER JOIN
                     professor AS p ON p.department_id=d.id
                GROUP BY d.name
            ) AS t
)

-- all depts with highest avg sal
SELECT dept, avg_sal
FROM x
WHERE rnk = 1

答案 2 :(得分:1)

您可以查询MAX(avgSalary)的子查询。我在这里做的就是使用CTE。

WITH cte AS
(
SELECT DEPARTMENT_ID
      ,AVG(SALARY) [avgSalary]
  FROM PROFESSOR
GROUP BY DEPARTMENT_ID
)

SELECT D.[NAME]
      ,cte.avgSalary
  FROM cte INNER JOIN DEPARTMENT D
            ON D.ID = cte.DEPARTMENT_ID    
 WHERE cte.avgSalary = (SELECT MAX(avgSalary)
                          FROM cte) 

答案 3 :(得分:0)

我认为你想要的是:

select
  NAME,
  max(avg_salary) as max_avg_salary
from
  DEPARTMENT d inner join
  (select
    DEPARTMENT_ID ,
    avg(SALARY) as avg_salary
  from
    PROFESSOR 
  group by
    DEPARTMENT_ID) a on
  d.DEPARTMENT_ID = a.DEPARTMENT_ID

正如您在其他答案中看到的那样,还有其他方法可以执行此操作,但我认为您希望使用group by来确定最简单的解决方案,以确定每个avgmax所有avg s。只有你需要的其他东西才是你可能熟悉的子查询。

HTH