I am trying to practise from hackerrank challenges but not able to understand the query. Here is the questions 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.
here is the link to the problem -https://www.hackerrank.com/challenges/harry-potter-and-wands/problem?isFullScreen=true
here is the solution which I could not understand
SELECT w.id, wp.age, w.coins_needed, w.power
FROM wands w INNER JOIN wands_property wp ON w.code = wp.code
WHERE wp.is_evil = 0 AND w.coins_needed = (SELECT MIN(w2.coins_needed)
FROM wands w2 INNER JOIN wands_property wp2 ON w2.code = wp2.code
WHERE w2.code = w.code AND wp2.is_evil = 0 AND w2.power = w.power)
ORDER BY w.power DESC, wp.age DESC;
(SELECT w.id, wp.age, w.coins_needed, w.power
FROM wands w INNER JOIN wands_property wp ON w.code = wp.code
WHERE wp.is_evil = 0)
Also kindly explain it using the with clause
I would highly appreciate your suggestion
Just find the cheapest wand and order by power and age.
select id
, age
, coins_needed
, power
from (
SELECT w.id
, wp.age
, w.coins_needed
, w.power
, ROW_NUMBER() over(partition by wp.age,w.power order by w.coins_needed) orderNum
FROM wands w
INNER JOIN wands_property wp ON w.code = wp.code
WHERE wp.is_evil = 0
) a
where a.orderNum = 1
order by power desc, age desc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.