Milky's note

[HackerRank](M) Placements 본문

SQL/SQL 코딩 테스트-HackerRank

[HackerRank](M) Placements

밀뿌 2022. 3. 31. 15:33

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

 

 

[답]

- mysql

select sp.name from
(select s.id, s.name, p.salary from students s
join packages p
on s.id = p.id) sp
join (select f.id, f.friend_id, p.salary from friends f
join packages p
on f.friend_id = p.id) fp
on sp.id = fp.id
where sp.salary < fp.salary
order by fp.salary

문제에서 output에 대한 설명을 자세하게 해주었다.

학생과 친구, 연봉에 대한 테이블 3개가 있는데 친한 친구의 연봉이 높은 학생들의 이름을 친구의 연봉대로 오름차순 정렬을 해주는 문제이다.

내가 생각한 방법은 학생-연봉, 친구-연봉을 각각 조인해서 2개의 테이블로 만들어준 다음 다시 두 개의 테이블을 join해주어서 친구의 연봉이 학생의 연봉보다 큰 학생들의 이름을 출력하고 정렬도 그게 맞게 해주면 된다 !!!

문제를 혼자 다 풀고 다른 분들이 푼 것도 봤는데 나처럼 크게 조인을 하지 않고 package 테이블을 2번 조인 시켜서 깔끔하게 작성하신 분도 있었다.. ! 답은 맞는데 나도 쿼리를 깔끔하게 간결하게 짤 수 있는 생각을 더 해봐야겠다.

 

Comments