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).
세 개의 테이블이 주어집니다: Students, Friends, Packages.
- Students 테이블은 두 개의 열로 구성됩니다: ID와 Name
- Friends 테이블은 두 개의 열로 구성됩니다: ID와 Friend_ID (유일한 가장 친한 친구의 ID)
- Packages 테이블은 두 개의 열로 구성됩니다: ID와 Salary (월 1000달러 단위로 제공된 급여)
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.
친구가 본인보다 월급이 많은 학생들의 이름을 쿠러히하세요. 이름은 반드시 친구의 급여를 기준으로 정렬 되어야 합니다. 월급이 똑같다는 두 학생이 없다는 전제가 있습니다.
WITH MY AS(
SELECT P.ID, Name, Salary AS MY_S
FROM Students S
JOIN Packages P ON S.ID = P.ID
),
FRIEND AS(
SELECT F.ID, F.Friend_ID, Salary AS F_S
FROM Friends F
JOIN Packages P ON F.Friend_ID = P.ID
ORDER BY F.ID
)
SELECT M.Name
FROM MY M
JOIN FRIEND F ON F.ID = M.ID
WHERE MY_S < F_S
ORDER BY F_S
친구 급여를 구하고 학생 급여를 구했다. 비교적 쉽게 풀 수 있다. 다만 With절 두개 쓴게 좋은 쿼리인지 모르겠다. 아래는 클로드에게 부탁한 더 최적화 된 쿼리다.
SELECT S.Name
FROM Students S
JOIN Friends F ON S.ID = F.ID
JOIN Packages P ON S.ID = P.ID
JOIN Packages P2 ON F.Friend_id = P2.ID
WHERE P2.Salary > P.Salary
ORDER BY P2.Salary
어려운 쿼리도 아니다. 아직 갈길이 먼 거 같다.
<2025년 5월 5일 복습>
WITH My_Salary AS(
SELECT S.ID, S.name, P.Salary AS my_salary
FROM Students S
JOIN Packages P ON P.ID = S.ID
), Friend_Salary AS(
SELECT F.ID, F.Friend_ID, P.Salary AS friend_salary
FROM Friends F
JOIN Packages P ON F.Friend_ID = P.ID
)
SELECT MS.name
FROM My_Salary MS
JOIN Friend_Salary FS ON MS.ID = FS.ID
WHERE friend_salary > my_salary
ORDER BY friend_salary
복습... 쉽다....
'MYSQL > HakerRank_Medium' 카테고리의 다른 글
Print Prime Numbers (0) | 2025.04.24 |
---|---|
Symmetric Pairs 과 Self_Join (0) | 2025.04.22 |
SQL Project Planning과 Islands and Gaps 패턴 (0) | 2025.04.21 |
Contest Leaderboard (0) | 2025.04.21 |
Challenges 와 WITH 절 (0) | 2025.04.18 |