I am trying to practice sql by myself and I was solving the questions from the website hackerrank. I came across to this question called " Ollivander's Inventory " ( here's a link if you want to see the question in detail other than my explanation https://www.hackerrank.com/challenges/harry-potter-and-wands/problem)
Question goes as
"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."
I found the solution that was pretty close to my code but still there is a part that i didnt understand in this solution. Code is:
Select w.id,wp.age,w.coins_needed,w.power
from wands as w
INNER JOIN wands_property as wp
on w.code=wp.code
Where wp.is_evil!=1 AND w.coins_needed=(Select min(Wands.coins_needed)
from Wands
inner join Wands_Property
on Wands.code=Wands_Property.code
where Wands_Property.age=wp.age and Wands.power=w.power)
order by w.power desc, wp.age desc;
I didnt understand this part of the code.
AND w.coins_needed=(Select min(Wands.coins_needed)
from Wands
inner join Wands_Property
on Wands.code=Wands_Property.code
where Wands_Property.age=wp.age and Wands.power=w.power)
As I know (correct me if im wrong please) we coudlnt use min(wands.coins_needed) in the beginning of the query because after wards we would need to use group by clause and it would cause problem on w.id. But what is the reason why we used another join after the w.coins_needed=(Select min(Wands.coins_needed)? Any help would be appricated. Please show me where im thinking wrong.
Thanks!