# Ollivander’s Inventory

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.

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 .

Sample Input

Wands Table:

Wands_Property Table:

Sample Output

`9 45 1647 1012 17 9897 101 20 3688 815 40 6018 719 20 7651 611 40 7587 510 20 504 518 40 3312 320 17 5689 35 45 6020 214 40 5408 1`

Logic: Be aware of the question: ”by determining the minimum number of gold galleons needed to buy each non-evil wand of high power and age”. Hence, we have to create two copies of the Wands and Wands_Property tables to filter the minimum number of coins_needed.

Solution:

`select w.id, p.age, w.coins_needed, w.power from Wands as w join Wands_Property as pon w.code = p.codewhere w.coins_needed = (select min(coins_needed)                       from Wands w2 inner join Wands_Property p2                        on w2.code = p2.code                        where p2.is_evil = 0 and p.age = p2.age and w.power = w2.power)order by w.power desc, p.age desc;`

Reference

--

--

## More from JEN-LI CHEN IN DATA SCIENCE

My homepage to record my thought processes for solving SQL and Algorithm questions