문제출처 : https://www.hackerrank.com/challenges/harry-potter-and-wands/problem?isFullScreen=true
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 .
문제를 처음에 이해에 상당히 오랜 시간을 썼다.. 헤르미온느가 어쩌구 저쩌구 ..
쓸모없는 부분이라 생각된 부분을 생략하고 문제를 정리하면 다음과 같은 조건을 만족하는 레코드를 조회하면 되는 문제다.
위 조건을 만족하는 레코드를 찾는 문제이다.
해당 조건을 만족시키기 위해서 WHERE 절에 서브 쿼리를 작성하여 조건에 맞는 테이블을 가져오는 형태로 해결할 수 있는 문제이다.
그럼 해당 조건을 찾기 위한 쿼리문을 살펴보자.
SELECT W.id,
P.age,
W.coins_needed,
W.power
FROM Wands W
INNER JOIN Wands_Property P ON W.code = P.code
WHERE P.is_evil = 0
AND W.coins_needed = (SELECT MIN(W1.coins_needed)
FROM Wands W1
INNER JOIN Wands_Property P1 ON W1.code = P1.code
WHERE P1.is_evil = 0
AND W1.power = W.power
AND P1.age = P.age)
ORDER BY W.power DESC, P.age DESC
두 테이블을 조인하고, non-evil 조건을 만족하면서 같은 power,age 값을 가진 레코드 가운데 가장 작은 coin_needed 를 가진 레코드를 조회하여 조건에 맞는 레코드를 찾을 수 있었다.
여기서 서브쿼리 내의 조건문을 살펴보면 서브쿼리문에서 메인쿼리문의 테이블을 참조하고 비교하였다는 점이 나에게 색다르고, 이렇게도 사용할 수 있구나 하고 와닿았다.