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, and , then and .

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 45 (code 1):

The data for wands of age 40 (code 2):

The data for wands of age 20 (code 4):

The data for wands of age 17 (code 5):

select w.id, wp.age, w.coins_needed, w.power
from wands w
join Wands_Property wp on w.code = wp.code
where wp.is_evil = 0
and coins_needed = (
select min(coins_needed)
from wands w2
JOIN Wands_Property wp2 ON w2.code = wp2.code
WHERE w2.power = w.power AND wp2.age = wp.age AND wp2.is_evil = 0
)
ORDER BY w.power DESC, wp.age DESC;
두 개의 테이블이 주어집니다:
- Wands: 지팡이 id, code, 가격(coins_needed), 품질(power)
- Wands_Property: code, age, is_evil (0이면 착한 지팡이)
고려 사항:
- is_evil = 0인 지팡이만 고려
- 같은 (power, age) 조합에 대해 가장 저렴한 지팡이만 선택
- 결과는 power 기준 내림차순, age 기준 내림차순 정렬
풀이:
- 먼저 두 테이블을 code 기준으로 JOIN
- is_evil = 0 조건 적용
- 같은 power와 age를 가진 지팡이 중 coins_needed가 최소인 지팡이만 필터링
- 정렬 조건대로 출력
'Computer Science > SQL' 카테고리의 다른 글
SQL | HackerRank 각 해커의 챌린지별 최고 점수 합계 구하기 (0) | 2025.06.23 |
---|---|
SQL | HackerRank 가장 많이 챌린지를 만든 학생 구하기 (0) | 2025.06.22 |
SQL | HackerRank 코딩 대회에서 여러 문제를 만점 받은 참가자 찾기 (2) | 2025.06.20 |
SQL | HackerRank 성적에 따라 이름을 보여주는 리포트 만들기 CASE WHEN (0) | 2025.06.19 |
SQL | HackerRank ROW_NUMBER()와 COUNT(*) OVER()를 활용하여 중앙값(Median) 구하기 (0) | 2025.06.18 |