Description
Table: Employee
| Column Name | Type |
|---|---|
| id | int |
| name | varchar |
| salary | int |
| managerId | int |
idis the primary key (column with unique values) for this table.- Each row of this table indicates the ID of an employee, their
name,salary, andmanagerId-the ID of their manager.
Problem Statement
Write a solution to find the employees who earn more than their managers. Return the result table in any order. The result format is in the following example.
Example 1:
Input:
Employeetable:
| id | name | salary | managerId |
|---|---|---|---|
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | Null |
| 4 | Max | 90000 | Null |
Output:
| Employee |
|---|
| Joe |
Explanation: Joe is the only employee who earns more than his manager.
Solution
The problem can be divided into two main parts.
- Find managers for each employee.
- Find employees who has salary greater than their manager.
In order to find managers for each employee, you can perform self join based on employee.managerId = manager.id.
1SELECT e.name Employee e
2 JOIN Employee m
3 ON e.managerId = m.id;
The second part of the problem states that you need employees for whom the salary is greater than their manager’s salary. You can do this by comparing e.salary > m.salary.
Hence, the problem can be solved using below SQL query.
1SELECT
2 e.name Employee FROM Employee e
3 JOIN Employee m
4 ON e.managerId = m.id
5 WHERE e.salary > m.salary;


Comments