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
SELECT
S.Name
FROM Students AS S
LEFT JOIN Friends AS F ON S.ID=F.ID
LEFT JOIN Packages AS P ON S.ID = P.ID
LEFT JOIN Packages AS P_F ON F.Friend_ID = P_F.ID
WHERE
P_F.Salary > P.Salary
ORDER BY
P_F.Salary;
POINT!
[동일 테이블을 두 역할로 나눠 활용하는 기법]
- Packages 테이블 하나를 두 번 JOIN해서
- 한 번은 학생 자신의 급여로
- 한 번은 친구의 급여로
- 마치 두 개의 테이블처럼 활용하는 방식입니다.
즉, 같은 테이블을 별칭(alias)으로 나눠서 두 역할을 하도록 한 거죠.
- P → 자기 급여
- P_F → 친구 급여
이 덕분에 별도의 테이블을 만들 필요 없이 같은 테이블 내에서 비교가 가능하고,
P_F.Salary > P.Salary 조건으로 친구보다 적게 받은 학생만 쉽게 걸러낼 수 있습니다.
'코딩 테스트 > 02. SQL' 카테고리의 다른 글
| [Hacker Rank] SQL Intermediate 'The Report' (Medium) (0) | 2025.08.22 |
|---|---|
| [Hacker Rank] SQL Intermediate 'Weather Observation Station 5'(Medium) (0) | 2025.08.22 |
| [Hacker Rank] SQL Intermediate 'Weather Observation station 20' (Medium) (4) | 2025.08.18 |
| [Hacker Rank] SQL Intermediate 'New Companies' (Medium) (0) | 2025.08.18 |
| [Hacker Rank]SQL Basic 'Weather Observation Station 19 '(Medium) (0) | 2025.08.17 |