https://www.hackerrank.com/challenges/harry-potter-and-wands/problem?isFullScreen=true
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.
Input Format
The following tables contain data on the wands in Ollivander's inventory:
- Wands: The id is the id of the wand, code is the code of the wand, coins_needed is the total number of gold galleons needed to buy the wand, and power denotes the quality of the wand (the higher the power, the better the wand is).

- Wands_Property: The code is the code of the wand, age is the age of the wand, and is_evil denotes whether the wand is good for the dark arts. If the value of is_evil is 0, it means that the wand is not evil. The mapping between code and age is one-one, meaning that if there are two pairs.

Sample Input
Wands Table:

Wands_Property Table:

Sample Output
9 45 1647 10
12 17 9897 10
1 20 3688 8
15 40 6018 7
19 20 7651 6
11 40 7587 5
10 20 504 5
18 40 3312 3
20 17 5689 3
5 45 6020 2
14 40 5408 1
풀이
문제 자체의 난이도는 높지 않지만, 문제에 함정이 있는 문제더라. 단순 join을 하면 되겠지 했는데, determining the minimum number of gold galleons needed 이 부분이 함정이더라. 먼저 최소 금액을 가진 지팡이의 정보를 먼저 뽑고, 그 쿼리를 바탕으로 나머지 테이블을 조인해서 구해야 한다.
select wa.id, pr.age, t.coins_needed, t.power
from wands wa
inner join wands_property pr
on wa.code = pr.code
inner join
(
select w.code, w.power, min(w.coins_needed) as coins_needed
from wands w
inner join wands_property wp
on w.code = wp.code
where wp.is_evil = 0
group by 1, 2
) t
on wa.code = t.code and wa.coins_needed = t.coins_needed and wa.power = t.power
order by t.power desc, pr.age desc
'Data > HackerRank' 카테고리의 다른 글
HackerRank - Challenges (0) | 2022.03.02 |
---|---|
HackerRank - Weather Observation Station 20 (0) | 2022.03.02 |
HackerRank - Binary Tree Nodes (0) | 2022.03.02 |
HackerRank - The PADS (0) | 2022.03.01 |
HackerRank - Interviews (0) | 2022.03.01 |