[HackerRank] Ollivander's Inventory(join, 서브쿼리)

생각하는 마리오네트·2021년 9월 24일
0

SQL

목록 보기
17/39

문제설명

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

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).

ColumnType
idInteger
codeInteger
coins_neededInteger
powerInteger

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 .

ColumnType
codeInteger
ageInteger
is_evilInteger

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

어려웠던 점

먼저 어려웠던점은 조건을 어떻게 쿼리해야할지 가장 힘들었다.
태블릿에 조건을 하나하나 적어가면서 했는데 POWER가 높고 AGE가 높고 is_devil이0이면서 최소골드 갤리온 수 인것을 찾아야했다. 하지만 이조건을 어떻게 작성해야할지 너무 막막했다. 그러다가 서브쿼리를 생각하게 되고 같은 테이블을 통해 power와 age는 같은데 coins_needed는 min값이 되게 만들어주어 해결하게 되었다.

정답

SELECT W.id, P.age, W.Coins_needed, W.power FROM Wands W
    INNER JOIN Wands_Property P ON W.code = P.code
    WHERE P.is_evil = 0 
    AND W.coins_needed = (SELECT MIN(W2.Coins_needed) FROM Wands W2 INNER JOIN Wands_Property P2 ON W2.code = P2.code  WHERE P2.is_evil = 0 AND (W2.Power = W.power) AND (P2.age = P.age))
ORDER BY W.power DESC, P.age DESC
profile
문제를해결하는도구로서의"데이터"

0개의 댓글