2023. 5. 28. 23:47ㆍHackerRank-My SQL
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.
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
=> 헤르미온느가 제시한 조건(악 선향 아니고, POWER와 AGE가 높은 것들 중 COINS_NEEDED가 낮은 것)에 알맞은 WANDS의 ID, AGE, COINS_NEEDED, POWER를 쿼리하라. 정렬기준은 POWER, AGE 내림차순이다.
=> code와 age가 1 ㄷ 1로 매칭 돼 있다는 소리는, WANDS_PROPERTY의 prime key를 두 개로 쓸 수 있거나, JOIN시의 매칭키를 서로 대체할 수 있다는 의미
코드
SELECT
WA.id,
WP.age,
K.MC,
K.power
FROM
(SELECT
CODE,
POWER,
MIN(coins_needed) AS MC
FROM WANDS
GROUP BY CODE, POWER) AS K
INNER JOIN WANDS AS WA ON K.code = WA.code AND K.MC = WA.coins_needed
INNER JOIN WANDS_PROPERTY AS WP ON K.code = WP.code
WHERE WP.is_evil = 0
ORDER BY WA.POWER DESC, WP.AGE DESC;
- GROUP BY의 이유: 헤미의 조건은 AGE, POWER에 따른 지팡이의 가격(CONIS_NEEDED) 가 여러개 인데, 그 중 젤 싼 것들을 보겠다는 것이므로 (AGE, POWER)의 조합에 따라 테이블을 분류해야 한다.
- MIN(COINS_NEEDED) 구하기: (age,power)의 조합에서 min(coins_needed) 를 찾는것과
(code, power)의 조합에서 min(coins_needed)를 찾는게 같다. 이후 서브쿼리로 이용 - JOIN ON : 결합조건을 잘 선택해야함. 최소가격과, CODE 두 가지를 기준으로 JOIN한다.
노트
- 아직 JOIN을 자유자재로 다루지 못함. JOIN 이후의 테이블을 머릿속으로 그려보는 연습.
- LEFT JOIN, OUTER JOIN 등 의 개념을 정확히 파악할 것.
'HackerRank-My SQL' 카테고리의 다른 글
Prepare > SQL > Basic Join > Contest Leaderboard (0) | 2023.05.31 |
---|---|
Prepare > SQL > Basic Join > Challenges (0) | 2023.05.30 |
Prepare > SQL > Basic Join > Top Competitors (0) | 2023.05.26 |
Prepare > SQL > Basic Join > The Report (0) | 2023.05.25 |
Prepare > SQL > Basic Join > Population Census (0) | 2023.05.25 |