SQL & DB/HackerRank SQL Problem

[HackerRank SQL] Ollivander's Inventory

YSY^ 2021. 3. 1. 20:45

www.hackerrank.com/challenges/harry-potter-and-wands/problem

 

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.

Input Format

The following tables contain data on the wands in Ollivander's inventory:

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

  • 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,  and , then  and .

     


Answer

select id, age, w.coins_needed, w.power 
#  the minimum number of gold galleons 
from (select code, min(coins_needed) as coins_needed, power from wands group by code, power) as w
    join
    wands as m
    on w.code = m.code and w.power = m.power and w.coins_needed = m.coins_needed
    join
    wands_property as p
    on m.code = p.code
where p.is_evil = 0 #non-evil wand of high power and age
order by w.power desc, age desc

group by를 쓰면 coin_neeeded를 나타낼 수 있는 방법은 min등의 집계함수이다. 최소 gold를 출력해야하니 min을 활용한다.

Result

728x90
반응형