Please make use of my blog posts for learning purpose only and feel free to ask your questions in the comment box below in case of any doubt.
Click Here for the previous blog-post in the series.
Recommended SQL Courses:
SQL Problem Statement:
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, (code1, age1) and (code2, age2), then code1!=cod2 and age1!=age2.
Sample Input:
Wands Table:
Wands_Property Table:
Sample Output:
- The minimum number of galleons needed for wand(age=45, power=2) = 6020
- The minimum number of galleons needed for wand(age=45, power=10) = 1647
- The minimum number of galleons needed for wand(age=40, power=1) = 5408
- The minimum number of galleons needed for wand(age=40, power=3) = 3312
- The minimum number of galleons needed for wand(age=40, power=5) = 7587
- The minimum number of galleons needed for wand(age=40, power=7) = 6018
- The minimum number of galleons needed for wand(age=20, power=5) = 504
- The minimum number of galleons needed for wand(age=20, power=6) = 7651
- The minimum number of galleons needed for wand(age=20, power=8) = 3688
- The minimum number of galleons needed for wand(age=17, power=3) = 5689
- The minimum number of galleons needed for wand(age=17, power=10) = 9897
Solution: Using INNER JOIN & HAVING (MySQL Query):
- MIN is an aggregation function used to get the least (minimum) value of all the records in the column name passed to the function.
- JOIN and INNER JOIN are the same in SQL. It returns the records that have matching values in both tables.