我想筛选出每个部门薪水最高的记录。如果一个部门中有多条记录符合此条件,请将其全部保留。然后我编写SQL如下:
SELECT id, name, salary, departmentId
FROM Employee
GROUP BY departmentId
HAVING salary = MAX(salary)
但它不能正常工作。
员工
表:
+----+-------+--------+--------------+
| 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.
执行的结果是:
| id | name | salary | departmentId |
| -- | ----- | ------ | ------------ |
| 3 | Henry | 80000 | 2 |
但我预期的结果是这样的:
| 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. Analysis of cause is more important for me.