与 GROUP BY 子句一起使用的 MAX 函数

Posted

技术标签:

【中文标题】与 GROUP BY 子句一起使用的 MAX 函数【英文标题】:MAX function used with GROUP BY clause 【发布时间】:2016-03-24 21:07:16 【问题描述】:

我有包含员工姓名、薪水和部门的数据库。 我需要查询以获取每个部门中薪水最高的员工。

数据库:

create table test(
    employee_name VARCHAR(255),
    department VARCHAR(255),
    salary INT  
);

数据:

INSERT INTO test(employee_name, department, salary) VALUES 
("John", "DepartmentA", 1500),
("Sarah","DepartmentA", 1600),
("Romel","DepartmentA", 1400),
("Victoria","DepartmentB", 1400),
("Maria",   "DepartmentB", 1600);

我的尝试:

1.1 WHERE MAX(salary) = 工资按部门分组

SELECT employee_name, salary FROM test WHERE MAX(salary) = salary GROUP BY department;
ERROR 1111 (HY000): Invalid use of group function

1.2。当我用硬编码值替换 MAX(salary) 时,它会按我的预期工作:

SELECT employee_name, salary FROM test WHERE 1600 = salary GROUP BY department;
+---------------+--------+
| employee_name | salary |
+---------------+--------+
| Sarah         |   1600 |
| Maria         |   1600 |
+---------------+--------+
2 rows in set (0.00 sec)

    有子句的错误答案(单个结果,不是每个部门):

    SELECTemployee_name,salary FROM test GROUP BY Department HAVING MAX(salary)=salary;

    +---------------+--------+ |员工姓名 |工资 | +---------------+--------+ |玛丽亚 | 1600 | +---------------+--------+ 一组中的 1 行(0.00 秒)

我期望的结果:

Sarah, DepartmentA
Maria, DepartmentB

【问题讨论】:

【参考方案1】:

首先你要得到每个部门的最高薪水:

SELECT department, max(salary) as max_salary
FROM test
GROUP BY department

然后您可以将此子查询加入到测试表中:

SELECT t.*
FROM
  test t INNER JOIN (
    SELECT department, max(salary) as max_salary
    FROM test
    GROUP BY department
  ) d ON t.department=d.department AND t.salary=d.max_salary

【讨论】:

这是正确的答案(我正要发布,只是格式略有不同) 只需要纠正一件小事:GORUP BY -> GROUP BY【参考方案2】:

试试这个:

SELECT t1.employee_name, t1.department
FROM test t1 
INNER JOIN (SELECT t2.department, MAX(t2.salary) AS salary
            FROM test t2
            GROUP BY t2.department
          ) AS t2 ON t1.department = t2.department AND t1.salary = t2.salary;

【讨论】:

【参考方案3】:

您可以将相关子查询编写为:

select employee_name,
department,
salary 
from test T1 where T1.salary = (select max(T2.salary)
                                from test T2
                                where T1.department = T2.department
                                group by T2.department
                                )

demo

...但请注意,它会比不相关的等价物慢得多

【讨论】:

我测试了它,它似乎工作得很好。我投票赞成

以上是关于与 GROUP BY 子句一起使用的 MAX 函数的主要内容,如果未能解决你的问题,请参考以下文章

GROUP BY子句

GROUP BY 子句必须与聚合函数一起使用?

15group by子句与聚合函数

不能在 Group by/Order by/Where/ON 子句中使用 Group 或 Aggregate 函数(min()、max()、sum()、count()、...等)

MySQL5.5版本 MAX函数与Group By一起使用的注意事项

与 GROUP BY 子句一起使用时,如何修复“ORA-00932:不一致的数据类型:预期 - 得到 CLOB”?