Question
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, (code1, age1) and (code2, age2), then code1 != code2 and age1 != age2.
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
Explanation
The data for wands of age 20 (code 4):
- The minimum number of galleons needed for
wand(age = 20, power = 5) = 504 - The minimum number of galleons needed for
wand(age = 20, power = 6) = 7651 - The minimum number of galleons needed for
wand(age = 20, power = 8) = 3688
Summary
- non evil(is_evil = 0)이며, age와 power가 높고, coins_needed는 낮은 wands를 얻고자 한다.
- age, code 쌍을 기준으로, 해당 pair의 가장 낮은 coin값과 id를 출력한다.
Solve
select id, p.age, a.min_coin , w.power
from wands w
join wands_property p on w.code = p.code
join (select p.age age, min(w.coins_needed) min_coin , w.power power
from wands w
join wands_property p on w.code = p.code
where p.is_evil = 0
group by p.age, w.power) a
on p.age = a.age and w.power = a.power and coins_needed = min_coin
order by w.power desc, p.age desc
Issue
해당 문제에서의 키포인트는 (age, power)가 기준이 된다는 점이다.
해당 pair는 중복되면 안된다는 점을 간과해서 풀이의 시간이 소요되었다.
코드상의 coins_needed = min_coin으로 중복 pair들을 지워내서(가장 낮은 값만 출력하도록하여) 문제를 해결했다.
Source
'Study > SQL' 카테고리의 다른 글
PostgreSQL | Codility | SqlEventsDelta (0) | 2023.03.06 |
---|---|
MySQL | Temporary Table (0) | 2023.02.09 |
MySQL | HackerRank | Top Earners (0) | 2023.02.06 |
MySQL | HackerRank | Top Competitors (0) | 2023.01.31 |
MySQL | HackerRank | The Report (0) | 2023.01.30 |