具有多个聚合函数的Mysql查询

时间:2016-07-23 10:21:18

标签: mysql views

我有这张桌子:

EMPLOYEES(Code, Name, Surname, Type, Department, Salary)

我需要在没有使用视图的情况下显示工资总额最高的部门。那可能吗?有观点的解决方案是:

CREATE VIEW DEPEXPENSES (DEPNAME, EXPENSE) AS  
SELECT DEPARTMENT, SUM(SALARY)  
FROM EMPLOYEES  
GROUP BY DEPARTMENT

SELECT DEPNAME  
FROM DEPEXPENSES  
WHERE EXPENSE=(SELECT MAX(EXPENSE) FROM DEPEXENSES)  

感谢。

1 个答案:

答案 0 :(得分:1)

问题不太清楚,但我认为你想在不使用视图的情况下运行第二个查询。一个解决方案就是:

select
  DEPARTMENT,
  SUM(SALARY)  
from
  EMPLOYEES  
group by
  DEPARTMENT
having
  SUM(SALARY)=(
    select MAX(SALARY) from (
      select DEPARTMENT, SUM(SALARY) as SALARY
      from EMPLOYEES  
      group by DEPARTMENT
    ) s
  )

(您可以在已包含聚合函数的子查询上应用最大聚合函数)