상세 컨텐츠

본문 제목

Employees Earning More Than Their Managers(LeetCode)

SQL/MySQL 문제풀이

by 관재탑 2022. 7. 20. 14:19

본문

https://leetcode.com/problems/employees-earning-more-than-their-managers/

 

Employees Earning More Than Their Managers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제

Table: Employee

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| salary      | int     |
| managerId   | int     |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.

 

Write an SQL query to find the employees who earn more than their managers.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+-------+--------+-----------+
| 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.

 

 

정답쿼리

SELECT e.name AS Employee
FROM Employee e
INNER JOIN Employee m ON e.managerID = m.id
WHERE e.salary > m.salary

 

 

해설

  • 문제에서 매니저보다 월급을 많이 받는 직원을 출력하라 했다. 
  • Self Join을 이용해 Employee테이블을 자기 자신과 Inner Join한다. Self Join을 할 때에는 Alias를 줘야한다.
  • e 테이블은 직원테이블, m 테이블은 매니저테이블로 하고 e.managerID를 키값으로 m테이블과 조인해서 매니저가 없는 직원들은 빼준다.
  • 직원과 매니저 테이블의 이름과 월급만 출력해준다.
  • WHERE e.salary > m.salary을 통해 매니저보다 월급을 많이 받는 직원만 출력해준다.
SELECT e.name AS Employee_name,
e.salary AS Employee_salary,
m.name AS Manager_name,
m.salary AS Manager_salary
FROM Employee e
INNER JOIN Employee m ON e.managerID = m.id
["Employee_name", "Employee_salary", "Manager_name", "Manager_salary"] 
["Joe", 70000, "Sam", 60000]
["Henry", 80000, "Max", 90000]

 

'SQL > MySQL 문제풀이' 카테고리의 다른 글

Symmetric Pairs(HackerRank)  (0) 2022.07.20
Rising Temperature(LeetCode)  (0) 2022.07.20
Customers Who Never Order(LeetCode)  (0) 2022.07.20
Reformat Department Table(LeetCode)  (0) 2022.07.20
Type of Triangle(HackerRank)  (0) 2022.07.18

관련글 더보기

댓글 영역