본문 바로가기

Database/SQL

Hackerrank / Placements

https://www.hackerrank.com/challenges/placements/problem?isFullScreen=true 

 

Placements | HackerRank

Write a query to output the names of those students whose best friends got offered a higher salary than them.

www.hackerrank.com

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.

Sample Input

 

Sample Output

Samantha
Julia
Scarlet


Explanation

See the following table:

Now,

  • Samantha's best friend got offered a higher salary than her at 11.55
  • Julia's best friend got offered a higher salary than her at 12.12
  • Scarlet's best friend got offered a higher salary than her at 15.2
  • Ashley's best friend did NOT get offered a higher salary than her

The name output, when ordered by the salary offered to their friends, will be:

  • Samantha
  • Julia
  • Scarlet

 

Solution #MySQL

select A.Name 
from (select S.ID, S.Name, P1.Salary
    from Students S join Packages P1
    on S.ID=P1.ID) A
join (select F.ID, F.Friend_ID, P2.Salary
     from Friends F join Packages P2
     on F.Friend_ID=P2.ID) B
on A.ID=B.ID
where A.Salary<B.Salary
order by B.Salary asc

Join으로 해결 가능했고

정답은 Friend의 Salary값을 오름차순 정렬한 후, 당사자 Name을 출력하면되는 문제였다.

 

'Database > SQL' 카테고리의 다른 글

Hackerrank / Weather Observation Station 18  (0) 2022.05.23
Hackerrank / Symmetric Pairs  (0) 2022.04.29
Hackerrank / Ollivander's Inventory  (0) 2022.01.22
Hackerrank / The Report  (0) 2022.01.22
Hackerrank / New Companies  (0) 2021.12.03