반응형
▶ 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로 조건을 적용하고, 최종적으로 이름을 뽑아냄
반응형
'CODING TEST > SQL : HackerRank' 카테고리의 다른 글
[MYSQL] New Companies (2) | 2022.09.30 |
---|---|
[MYSQL] Weather Observation Station 13 (0) | 2021.08.16 |
[MYSQL] Weather Observation Station 2 (0) | 2021.08.09 |
[MYSQL] Top Earners (0) | 2021.05.26 |
[MYSQL] The Blunder (0) | 2021.05.18 |
[MYSQL] Population Density Difference (0) | 2021.05.13 |
[MYSQL] Japan Population (0) | 2021.05.13 |
[MySQL] Average Population (0) | 2021.04.21 |
댓글