20. Employees with the Highest Salary in Each Department
We have two tables: Employee and Department.
Table: Employee
āāāāāāāāāāāāāāāā¦āāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāāā¬āāāāāāāāā⣠ā id ā int ā āāāāāāāāāāāāāāāā¼āāāāāāāāāā ā name ā varchar ā āāāāāāāāāāāāāāāā¼āāāāāāāāāā ā salary ā int ā āāāāāāāāāāāāāāāā¼āāāāāāāāāā ā departmentId ā int ā āāāāāāāāāāāāāāāā©āāāāāāāāāā
- id is the primary key for the Employee table.
- departmentId is a foreign key that references the id of the Department table.
- Each row in this table represents an employee's id, name, salary, and the id of the department they belong to.
Table: Department
āāāāāāāāāāāāāāā¦āāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāā⣠ā id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāā ā name ā varchar ā āāāāāāāāāāāāāāā©āāāāāāāāāā
- id is the primary key for the Department table. It is guaranteed that the department name is not NULL.
- Each row in this table contains the id and name of a department.
Task:
Your task is to find the employees who have the highest salary in each department. The result should be ordered by salary in descending order. If two or more employees have the same salary, order them by employee name in ascending order.
Example 1:
Example
Input:
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 ā āāāāāā©āāāāāāāā©āāāāāāāāā©āāāāāāāāāāāāāāā
Department table:
āāāāāā¦āāāāāāāā ā id ā name ā ā āāāāā¬āāāāāāā⣠ā 1 ā IT ā āāāāāā¼āāāāāāāā ā 2 ā Sales ā āāāāāā©āāāāāāāā
Output:
āāāāāāāāāāāāāā¦āāāāāāāāāāā¦āāāāāāāāā ā Department ā Employee ā Salary ā ā āāāāāāāāāāāāā¬āāāāāāāāāāā¬āāāāāāāā⣠ā IT ā Jim ā 90000 ā āāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāā ā IT ā Max ā 90000 ā āāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāā ā Sales ā Henry ā 80000 ā āāāāāāāāāāāāāā©āāāāāāāāāāā©āāāāāāāāā
Explanation:
For the IT department, both Jim and Max have the highest salary of 90000.
For the Sales department, Henry has the highest salary of 80000.
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.