CODING TEST/SQL : HackerRank

[MYSQL] Placements

주 녕 2022. 10. 5. 01:49
728x90

▶ SQL  >  Advanced Join > Placements

 

 Problem 

You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).

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.

→ 자신의 베프가 더 많은 봉급을 받는 학생의 이름을 쿼리하라 ... 🥲 

→ 베프의 봉급 순으로 나열하라 (같은 봉급을 받는 학생은 없음을 보장)

 

 My Answer 

SELECT BF.NAME
FROM (
    SELECT S.Name AS NAME, PS.Salary AS S_SALARY, F.id AS F_ID, PF.Salary AS F_SALARY
    FROM Students AS S 
        JOIN Packages AS PS ON S.id = PS.id
        JOIN Friends AS F ON S.id = F.id
        JOIN Packages AS PF ON F.Friend_id = PF.id) AS BF
WHERE BF.S_SALARY < BF.F_SALARY
ORDER BY BF.F_SALARY
  • 비교를 위한 서브 테이블을 만들어야 한다고 생각함 (Nested Query를 사용)
  • 같은 테이블을 2번 Join 해도 되는가에 의문이 들긴했지만 별칭을 다르게 하면 상관없을 것 같아서 한번 시도해봄
  • 비교를 위해 만든 BF 라는 베프 서브 테이블에 WHERE과 ORDER BY로 조건을 적용하고, 최종적으로 이름을 뽑아냄

 

728x90