[SQL] Ollivander's Inventory | Hackerrank

·2025년 2월 27일

SQL

목록 보기
20/23

문제

Hackerrank - Ollivander's Inventory

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.

  • wands
  • wands_property

요약

  • 좋은 지팡이의 기준: high power, high age, non-evil, minimum number of gold galleons
  • code와 age는 일대일 대응

풀이

📍point: power와 age가 같은 여러 개의 지팡이 중 가장 저렴한 지팡이를 출력해야 하는 문제
⚠️ window function이나 CTE 사용 시 hackerrank mysql 버전 문제로 오류 발생!

정답 쿼리

SELECT W.ID, WP.AGE, W.COINS_NEEDED, W.POWER
FROM WANDS AS W JOIN WANDS_PROPERTY AS WP ON W.CODE = WP.CODE
WHERE WP.IS_EVIL = 0
    AND W.COINS_NEEDED = (SELECT MIN(W2.COINS_NEEDED)
                          FROM WANDS W2 JOIN WANDS_PROPERTY WP2 ON W2.CODE = WP2.CODE
                          WHERE WP2.AGE = WP.AGE AND W2.POWER = W.POWER)
ORDER BY W.POWER DESC, WP.AGE DESC;
  1. Output 테이블에 필요한 컬럼과 조인된 테이블을 각각 SELECT절과 FROM 절에 입력
  2. evil한 지팡이는 제거해야 하므로 WHERE절에 첫 번째 조건으로 추가
  3. AGE와 POWER가 같은 지팡이의 최소 금액을 찾기 위해 WHERE절에 조건을 추가
    현재의 (AGE, POWER)와 같은 값을 가지는 지팡이들 중 Coins_needed외 최솟값을 구하는 쿼리.
profile
To Dare is To Do

0개의 댓글