[SQL] Hackerrank - Olivander's Inventory

2023. 3. 31. 21:46공부/SQL

https://www.hackerrank.com/challenges/harry-potter-and-wands

Problem

더보기

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.

해석

Hermione는 최소한의 gole galleons 를 가지고 non-evil 이면서 high power 와 age를 가지고 있는 지팡이를 찾고 있다. 이 방법으로 쿼리를 작성하는데 출력해야 할 것은 id, age, coins_needed 와 power임 그리고 power의 수치로 내림차순 정렬해라. 동일한 power를 가질 경우 age 내림차순 적용

 

Condition

1. is_evil = 0 값인 non-evil 지팡이

2. Age, Power 값이 같은 지팡이라면 coins_needed가 낮아야함.

3. 앞에서 말한 정렬조건을 만족해야함.

 

 

Solution

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
ORDER BY w.power DESC, p.age DESC;

여기까지는 별 어려움 없이 작성되었다. non-evil 이면서 정렬조건은 잘 만족할것 같다.

 

하지만, coins_needed = min(coins_needed)이면서 높은 power와 age를 가진 지팡이를 구하려면, 서브쿼리를 사용해야할까? 이게 최선인가? 고민을 함. (wp.is_evil = 0은 쉬우니까 생략)

 

다른 방법이 생각나질 않아서 서브쿼리를 이용하기로함.

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 w.coins_needed = (
        SELECT MIN(sub_w.coins_needed) FROM Wands sub_w
            JOIN Wands_Property sub_wp ON sub_w.code = sub_wp.code
        WHERE sub_wp.is_evil=0
        AND sub_w.power = w.power 
        AND sub_wp.age = wp.age
    )
ORDER BY w.power DESC, wp.age DESC;

 

서브쿼리가 중요한 문제같았음.

 

 

'공부 > SQL' 카테고리의 다른 글

[SQL] HackerRank - Project Planning  (0) 2023.04.05
[SQL] Hackerrank - Binary Tree Nodes  (0) 2023.04.02
[SQL] HACKERRANK - TOP COMPETITORS  (0) 2023.03.31
[SQL] HAKERRANK - THE REPORT  (0) 2023.03.31
[SQL] 문제풀이 TYPE OF TRIANGLE  (0) 2023.03.31