Trample Diary 184. The highest paid employee in the department

topic
Insert picture description here
Insert picture description here

At first, my idea was to
use group by to group in max (Salary), but in this way, only one query with the highest salary and the same salary can be output.

Then changed my mind

First, query the maximum salary of each department according to the department sub-leasing,
select DepartmentId , max(Salary) from Employee f group by f.DepartmentId
and then associate the two tables to query the maximum value according to the department id and price.
However, the first pass of SQL is written like this

select 
d.Name Department,
e.Name Employee,
Salary 
from
 Employee e 
 join
Department d on  e.DepartmentId=d.Id 
where 
(e.DepartmentId,e.Salary) in
(select DepartmentId , max(Salary) from Employee  group by e.DepartmentId)

This query can only query the highest salary of a department. After various queries and inspections, after half an hour, the root cause
is finally found . When querying the maximum price,
select DepartmentId, max(Salary) from Employeegroup by e.DepartmentId
can only be queried. The price of 9000,
so it passed the test after modification

select 
d.Name Department,
e.Name Employee,
Salary 
from
 Employee e 
 join
Department d on  e.DepartmentId=d.Id 
where 
(e.DepartmentId,e.Salary) in
(select DepartmentId , max(Salary) from Employee f  group by f.DepartmentId)

Write this blog to commemorate this pit! !

Guess you like

Origin blog.csdn.net/wlj1442/article/details/109367863