[SQL] Hackerrank - Placements

2023. 4. 5. 20:09공부/SQL

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

Tables

 

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.

 

해석해보자면.. 자신보다 높은 급여를 제안 받은 친구가 존재하는 학생(자신)의 이름들을 출력해라. 정렬조건은 자신보다 높은 급여를 제안받은 친구의 급여를 오름차순을 기준으로한다.

 

SOLUTION

 

문제를 해결하기 위해서 필요한건 나의 Salary와 친구의 Salary를 비교하기 위해서 join 또는 subquery를 사용

나의 Salary 구하는방법과 친구의 Salary 구하는 방법을 먼저 작성해봐야할것

 

s.id = p.id 인 경우 나의 salary를 구할 수 있고,

f.friend_id = p.id인 경우 친구의 salary를 구 할 수 있다.

 

두가지의 salary가 필요하니 salary AS my_salary와 salary AS friend_salary로 나누려면... inner JOIN Packages를 두번해야되나?

 

한번 해봅시다.

 

SELECT name 
FROM (
    SELECT 
        name, 
        p1.salary AS my_salary, 
        p2.salary AS friend_salary
    FROM Students s
    JOIN Friends f ON s.ID = f.ID
    JOIN Packages p1 ON s.ID = p1.ID
    JOIN Packages p2 ON f.friend_id = p2.ID 
) sub
WHERE friend_salary>my_salary
ORDER BY friend_salary

생각보다 간단하게 해결