새소식

SQL/해커랭크

[MySQL] Ollivander's Inventory

  • -

[문제]

Ollivander's Inventory | HackerRank

 

Ollivander's Inventory | HackerRank

Help pick out Ron's new wand.

www.hackerrank.com


[문제 풀이]

문제가 요구하는 것을 정확히 파악하지 못해서 헤매어서 풀었던 문제.

 

문제에서 요구하는 것은 1. is_evil 은 0이어야 한다. 2. 만약 age와 power가 같다면 coins_needed가 작은 값만을 가져와야 한다.

1번은 바로 이해가 되었는데 2번을 바로 파악을 못해서 헤맸었다.

 

JOIN을 쓰고 SELECT 부분에서 한번 더 JOIN 으로 power와 age가 일치하고 evil은 0인 최소 값의 coins_needed를 가져오자.

밑에서 A2.power = A.power는 GROUP BY 와 비슷한 효과를 낸다.

 

*GROUP BY를 사용해서도 풀어보자.

 


[코드]

SELECT A.id, B.age, A.coins_needed, A.power FROM Wands as A JOIN Wands_Property as B on B.code = A.code WHERE B.is_evil = 0 and A.coins_needed = (SELECT MIN(A2.coins_needed) FROM Wands as A2 JOIN Wands_Property as B2 on A2.code = B2.code WHERE B2.is_evil = 0 and A2.power = A.power and B2.age = B.age) ORDER BY A.power DESC, B.age DESC;

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.