Ollivander’s Inventory SQL – Hacker Rank Solution

Ollivander's Inventory SQL - Hacker Rank Solution
Ollivander’s Inventory SQL – Hacker Rank Solution

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 idagecoins_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). 1458538092 b2a8163a74 ScreenShot2016 03 08at12.13.39AM
  • 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 .1458538221 18c4092b7d ScreenShot2016 03 08at12.13.53AM

Sample Input

Wands Table: 1458538559 51bf29644e ScreenShot2016 03 21at10.34.41AM Wands_Property Table: 1458538583 fd514566f9 ScreenShot2016 03 21at10.34.28AM

Sample Output

9 45 1647 10
12 17 9897 10
1 20 3688 8
15 40 6018 7
19 20 7651 6
11 40 7587 5
10 20 504 5
18 40 3312 3
20 17 5689 3
5 45 6020 2
14 40 5408 1


Ollivander’s Inventory SQL – Hacker Rank Solution

SELECT a.id,
   b.age,
   a.coins_needed,
   a.power
FROM   wands a
   JOIN wands_property b
     ON a.code = b.code
WHERE  b.is_evil = 0
    AND a.coins_needed = (SELECT Min(a1.coins_needed)
    FROM   wands a1
        JOIN wands_property b1
          ON a1.code = b1.code
    WHERE  b.age = b1.age
        AND a.power = a1.power)
ORDER  BY a.power DESC,
          b.age DESC;

Disclaimer: The above Problem (Ollivander’s Inventory) generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment