提问者:小点点

如何找到每个部门工资最高的员工?[重复]


CREATE TABLE employees(id int AUTO_INCREMENT PRIMARY KEY, emp_name VARCHAR(10), dept VARCHAR(10), salary DECIMAL(8,2));

INSERT INTO employees (dept,emp_name,salary) VALUES('Engg','Sam',1000);
INSERT INTO employees (dept,emp_name,salary) VALUES('Engg','Smith',2000);
INSERT INTO employees (dept,emp_name,salary) VALUES('HR','Denis',1500);
INSERT INTO employees (dept,emp_name,salary) VALUES('HR','Danny',3000);
INSERT INTO employees (dept,emp_name,salary) VALUES('IT','David',2000);
INSERT INTO employees (dept,emp_name,salary) VALUES('IT','John',3000);
INSERT INTO employees (dept,emp_name,salary) VALUES('Sales','Ravi',4000);
INSERT INTO employees (dept,emp_name,salary) VALUES('Sales','Bob',6000);
INSERT INTO employees (dept,emp_name,salary) VALUES('HR','Rick',4500);
INSERT INTO employees (dept,emp_name,salary) VALUES('IT','Mathew',2500);

表:雇员

+----+----------+-------+---------+
| id | emp_name | dept  | salary  |
+----+----------+-------+---------+
|  1 | Sam      | Engg  | 1000.00 |
|  2 | Smith    | Engg  | 2000.00 |
|  3 | Denis    | HR    | 1500.00 |
|  4 | Danny    | HR    | 3000.00 |
|  5 | David    | IT    | 2000.00 |
|  6 | John     | IT    | 3000.00 |
|  7 | Ravi     | Sales | 4000.00 |
|  8 | Bob      | Sales | 6000.00 |
|  9 | Rick     | HR    | 4500.00 |
| 10 | Mathew   | IT    | 2500.00 |
+----+----------+-------+---------+

问题:

查找每个部门工资最高的员工

输出:

+----+----------+-------+---------+
| id | emp_name | dept  | salary  |
+----+----------+-------+---------+
|  8 | Bob      | Sales | 6000.00 |
|  9 | Rick     | HR    | 4500.00 |
|  6 | John     | IT    | 3000.00 |
|  2 | Smith    | Engg  | 2000.00 |
+----+----------+-------+---------+

当我尝试时,我会犯很多错误。为什么会出现错误?

SELECT id, emp_name, salary, dept 
FROM employees 
GROUP BY dept;

预期结果:

+----+----------+-------+---------+
| id | emp_name | dept  | salary  |
+----+----------+-------+---------+
|  8 | Bob      | Sales | 6000.00 |
|  9 | Rick     | HR    | 4500.00 |
|  6 | John     | IT    | 3000.00 |
|  2 | Smith    | Engg  | 2000.00 |
+----+----------+-------+---------+

实际结果:

错误1055(42000):SELECT列表的表达式#1不在GROUP BY子句中,并且包含未聚合的列“test#db”。员工。ID',在功能上不依赖于GROUP BY子句中的列;这与sql\u mode=only\u full\u group\u by不兼容


共1个答案

匿名用户

您应该使用以下查询:

SELECT A.*
FROM EMPLOYEES A
JOIN (
  SELECT DEPT, MAX(SALARY) SALARY
  FROM EMPLOYEES
  GROUP BY DEPT
) B ON A.SALARY = B.SALARY AND A.DEPT = B.DEPT