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

时间:2015-12-18 07:54:34

标签: mysql sql select group-by aggregate-functions

我有名字,工资和员工部门的数据库。 我需要一个查询来获得每个部门薪水最高的员工。

数据库:

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(薪水)=工资GROUP BY部门

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

1.2。当我用硬编码的值替换MAX(薪水)时,它可以正常工作:

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)
  1. 有条款的错误答案(单个结果,不是每个部门):

    SELECT employee_name,salary FROM test GROUP BY department HAVING MAX(薪水)=工资;

    + --------------- + -------- +     | employee_name |工资|     + --------------- + -------- +     |玛丽亚| 1600 |     + --------------- + -------- +     1行(0.00秒)

  2. 我期望的结果是:

    Sarah, DepartmentA
    Maria, DepartmentB
    

3 个答案:

答案 0 :(得分:5)

首先,您必须获得每个部门的最高薪水:

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

答案 1 :(得分:1)

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

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

...但请注意,它会比不相关的等效物

慢得多

答案 2 :(得分:0)

试试这个:

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;