[Leet Code] Employees Earning More Than Their Managers

정보희·2022년 3월 25일
0

SQL 공부

목록 보기
6/8

+-------------+---------+
| 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.

#SELF JOIN
+----+-------+--------+-----------+
| id | name | salary | managerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | Null |
| 4 | Max | 90000 | Null |
+----+-------+--------+-----------+

이렇게 되어있는 표 A 를
MAGAGERID 기준으로 작성되어 있는 표 B 로 하나 더 만들고 나서
A,B 를 기준으로 조인을 한다고 생각해보자

SELECT * FROM Employee 
     INNER JOIN Employee AS B ON Employee. id=B. managerId

ㄴ기존 Employee 랑 B 라고 정의한 Employee 같은 컬럼을 조인할거야
다만 가지고 오는 기준 칼럼은 달라,하나는 그냥 id, B는 매니저의 ID

[틀린쿼리]

SELECT Employee.Name as Emplyee 
       ,Employee.salary as Employee_salary
       ,B.Name as B_Name
       ,B.salary as  B_salary
     FROM Employee 
     INNER JOIN Employee AS B ON Employee. id=B. managerId

/ ["Emplyee", "Employee_salary", "B_Name", "B_salary"
["Sam", 60000, "Joe", 70000],
["Max", 90000, "Henry", 80000]}
/

ㄴ 원래 eMPLOYEE 랑 B 랑 순서가 바뀐 느낌인데...? 쌤이랑 맥스가 매니저거든1 

```

SELECT Employee.Name as Emplyee
,Employee.salary as Employee_salary
,B.Name as B_Name
,B.salary as B_salary
FROM Employee
INNER JOIN Employee AS B ON Employee.managerId=B.Id

    ***INNER JOIN Employee AS B ON Employee.managerId=B.Id 순서 주의
    
    
    
    
    [정답 쿼리]
    ```
SELECT Employee.Name as Employee 
     FROM Employee 
     INNER JOIN Employee AS B ON Employee.managerId=B.Id
     where Employee.salary>B.salary
     
profile
데이터 다루는 마케터가 되는 것이 꿈 입니다!

0개의 댓글

관련 채용 정보