문제 )
Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.
(자세한 문제는 이곳을 참고해 주세요! Placements
문제를 요약해보면 다음과 같습니다! 각각 학생마다 Best Friend가 존재하는데요. 해당하는 Best Friend 가 본인의 Salay 보다 높은 학생들의 이름을 추출하는 쿼리를 작성하는 문제 입니다. 아래의 예시를 참고하면 더 이해하기 쉽습니다.
Explanation
Samantha , Julia, Scarlet 의 경우 본인보다 friend 의 salary가 높고, Ashley 의 경우 friend보다 본인이 더 높은 salary를 받기 때문에 , Samantha, Julia, Scarlet만 나오도록 쿼리를 작성해야 합니다.
SELECT A.NAME
-- ,S.NAME as friend_name
-- ,P.Salary as friend_sal
FROM ( SELECT S.*
, P.SALARY
, F.FRIEND_ID
FROM STUDENTS S1
JOIN FRIENDS F ON S.ID = F.ID
JOIN PACKAGES P ON P.ID = S.ID ) A
JOIN STUDENTS S ON A.FRIEND_ID = S.ID
JOIN Packages P ON P.ID = A.FRIEND_ID
WHERE A.Salary < P.Salary
ORDER BY P.Salary
풀이과정
- 일단 자기자신(id)에 대한 Name, Salary 그리고 해당하는 Friend의 id 를 구해야하기 때문에 위에서 제공된 3개의 테이블을 join 해 줍니다. join key = id
- 그렇다면 아래와 같은 테이블
A
가 먼저 만들어지는데. friend_id 의 salary를 비교해야 하기 때문에
friend_id에 따라 한번 더 똑같이 join 을 해줘야 friend_id에 대응하는 name,salary를 구할 수 있습니다.- 주어진 조건에 따라 A.Salary < P.Salary , 즉 본인 Salary 보다 friend 의 Salary가 큰 경우의 Name만 추출하고, Friend 의 Salary 오름차순으로 나열해줍니다.
A
id | name | salary | friend_id |
---|---|---|---|
1 | Ashely | 15.2 | 2 |
2 | Samantha | 10.06 | 3 |
3 | julia | 11.55 | 4 |
4 | scalet | 12.12 | 1 |
id | name | salary | friend_id | friend_name | friend_sal |
---|---|---|---|---|---|
1 | Ashely | 15.2 | 2 | Samantha | 10.06 |
2 | Samantha | 10.06 | 3 | julia | 11.55 |
3 | julia | 11.55 | 4 | scalet | 12.12 |
4 | scalet | 12.12 | 1 | Ashely | 15.2 |