문제 사이트
아래 문제는 해커랭크에서 추출해온 문제입니다. 문제의 저작권은 해커랭크에 있으며 문제를 풀어보시려면 아래 링크를 클릭해주세요 🙂
Ollivander's Inventory | HackerRank
Help pick out Ron's new wand.
www.hackerrank.com
문제 설명
Harry Potter and his friends are at Ollivander's with Ron, finally replacing Charlie's old broken wand.
Hermione decides the best way to choose is by determining the minimum number of gold galleons needed to buy each non-evil wand of high power and age. Write a query to print the id, age, coins_needed, and power of the wands that Ron's interested in, sorted in order of descending power. If more than one wand has same power, sort the result in order of descending age.
🎙️해리포터와 친구들은 론과 함께 찰리의 오래되고 부서진 지팡이를 교체하기 위해 Ollivander's에 있다.
헤르미온느는 non-evil 지팡이이면서 높은 파워와 age를 가진 지팡이를 사는데 필요한 최소한의 골드를 고르는 최선의 방법을 제안했다.
론이 관심있어하는 지팡이의 id, age, coins_needed, power 를 출력하는 쿼리를 작성하고 이를 power 내림차순으로 정렬해라. 만약 똑같은 power를 가진 지팡이가 한 개 이상이라면, age 내림차순으로 정렬하라.
문제 풀이
문제를 요약하자면 조건에 만족하는 지팡이의 최소값을 찾는 문제이다.
따라서 먼저 생각해야 할 조건은
1. non-evil : Wands_Property의 is_evil = 0 이어야 함
2. coins_needed 최솟값 : Age와 power가 같은 항목들 중 coins_needed가 최소인 항목을 찾아야 함
3. 정렬기준 만족 : power desc -> age desc
👉 coins_needed의 최솟값을 뽑는 서브쿼리를 만든 후, coins_needed = min(coins_needed)를 만족하는 행 추출하기
추가 : code가 다를 경우, age값도 다름
문제 풀이 과정
1. 출력해야 하는 값과 non_evil 조건에 만족하는 쿼리를 먼저 작성
select w.id,
wp.age,
w.coins_needed,
w.power
from Wands w inner join Wands_Property wp
on w.code = wp.code
where wp.is_evil = 0
2. power, age별 min(coins_needed)를 만족하는 서브쿼리 작성
select min(w1.coins_needed)
from Wands w1 inner join Wands_Property wp1
on w1.code = wp1.code
where wp1.is_evil = 0
and w1.power = w.power
and wp1.age = wp.age)
3. power -> age 순으로 내림차순 정렬
최종 답안
select w.id,
wp.age,
w.coins_needed,
w.power
from Wands w inner join Wands_Property wp
on w.code = wp.code
where wp.is_evil = 0 and w.coins_needed = (select min(w1.coins_needed)
from Wands w1 inner join Wands_Property wp1
on w1.code = wp1.code
where wp1.is_evil = 0
and w1.power = w.power
and wp1.age = wp.age)
order by 4 desc, 2 desc
'SQL > MySQL' 카테고리의 다른 글
[MySQL] HackerRank - Contest Leaderboard 문제 풀이 (3) | 2024.08.28 |
---|---|
[MySQL] HackerRank - Challenges 문제 풀이 (0) | 2024.08.16 |
[MySQL] HackerRank - Top Competitors 문제 풀이 (0) | 2024.07.31 |
[MySQL] 프로그래머스 SQL 문제 + 정답, String, Date 문 (0) | 2024.06.25 |
[MySQL] 프로그래머스 SQL 문제 + 정답, JOIN 문 (0) | 2024.06.18 |