I want to filter out the record with the highest salary for each department. If there are multiple records that meet this condition in a department, keep all of them.Then I write SQL following:
SELECT id, name, salary, departmentId
FROM Employee
GROUP BY departmentId
HAVING salary = MAX(salary)
But it’s not working correctly.
the Employee
table:
+----+-------+--------+--------------+
| id | name | salary | departmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+
id is the primary key column for this table.
The result of the execution is:
| id | name | salary | departmentId |
| -- | ----- | ------ | ------------ |
| 3 | Henry | 80000 | 2 |
But the result that I expected is like this:
| id | name | salary | departmentId |
| -- | ----- | ------ | ------------ |
| 2 | Jim | 90000 | 1 |
| -- | ----- | ------ | ------------ |
| 3 | Henry | 80000 | 2 |
| -- | ----- | ------ | ------------ |
| 5 | Max | 90000 | 1 |
I want to know why I can’t get the result that I expect? what’s wrong with my SQL? I know how to write the correct SQL statement now. I just want to know what exactly is wrong with my SQL statement.
2
Answers
You can have this by using a subquery to find the max salary with respect to the department.
OR
This answer also works for MySQL 5.6
If you are using MySQL 8.X, you have your answer already in the comment section
this will give you the desired output.