안녕하세요!
해커랭크에 있는 Placements 문제입니다.
- 문제
자신보다 급여가 많은 친구가 있는 사람의 이름을 조회해야 한다.
이름은 친구의 급여를 기준으로 오름차순으로 정렬하면 되겠습니다.
(친구와 비교를 해야 한다니 문제가 잔인하네요.)
- 테이블
- 쿼리
1. 조인, 서브쿼리 사용
select name
from students s
inner join packages p
on s.id = p.id
inner join (select f.id, friend_id, salary
from friends f
inner join packages p on f.friend_id = p.id) f
on s.id = f.id
where p.salary < f.salary
order by f.salary
1) 본인의 급여를 알기 위해 students, packages 테이블을 결합.
2) 친구의 급여를 알기 위해 friends, packages 테이블을 friend_id 기준으로 결합.
3) 결합된 두 개의 테이블을 본인 id 기준으로 결합.
4) where 조건 절에서 salary를 비교, 친구의 급여를 기준으로 정렬.
2. with 문 사용
with my as (
select s.id, s.name, p.salary
from students s
inner join packages p
on s.id = p.id)
, friend as (
select f.id, friend_id, salary
from friends f
inner join packages p on f.friend_id = p.id)
select my.name
from my
inner join friend on my.id = friend.id
where my.salary < friend.salary
order by friend.salary
1) my 테이블엔 본인의 id, name, salary
2) friend 테이블엔 본인의 id, 친구의 id, salary
3) my 테이블과 friend 테이블을 본인 id 를 기준으로 결합
4) my.salary 와 friend.salary 비교, friend.salary 기준 정렬
- 출처 : https://www.hackerrank.com/challenges/placements/problem?isFullScreen=true
'배우기 > SQL' 카테고리의 다른 글
SQL 조인(INNER / LEFT / RIGHT JOIN) 알아보기_MySQL (0) | 2022.04.24 |
---|---|
HackerRank - Contest Leaderboard(조인, 서브쿼리)_MySQL (0) | 2022.04.21 |
Leetcode - 180.Consecutive Numbers(조인)_MySQL (0) | 2022.04.18 |
HackerRank - The Report(CASE WHEN/조인, BETWEEN)_MySQL (0) | 2022.04.18 |
HackerRank - Top Competitors (조인)_MySQL (0) | 2022.04.11 |
댓글