[SQL] HackerRank > Ollivander's Inventory

eun·2022년 6월 4일
0

HackerRank

목록 보기
5/7
post-thumbnail

Ollivander's Inventory


Link

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

1) by determining the minimum number of gold galleons

2) needed to buy each non-evil wand of high power and age.

3) Write a query to print the id, age, coins_needed, and power of the wands that Ron's interested in,

4) sorted in order of descending power.

5) If more than one wand has same power, sort the result in order of descending age.


Example

풀이


📌 주요 조건 정리

  • is_evil=0 값인 non-evil 지팡이들만 골라야 한다.
  • age, power 값이 각각 같은 지팡이들 중에서 coins_needed 값을 최소로 하는 지팡이를 골라야 한다.
  • 2개의 정렬 기준을 만족시켜야 한다.
  • Write a query to print the id, age, coins_needed, and power of the wands
  1. wands 테이블에서 code, power 별로 최솟값의 coins_needed 출력하기
( SELECT code, power, MIN(coins_needed) AS coins_needed
	FROM wands
	GROUP BY code, power ) s
1 2701 1 
1 4361 2 
1 3754 6 
1 909 7 
1 2302 8 
1 7322 10 
2 1467 1 
2 4436 2 
2 5222 3 
  1. id 칼럼을 불러오기 위해서 wands 테이블과 조인
FROM ( SELECT code, power, MIN(coins_needed) AS coins_needed
	   FROM wands
	   GROUP BY code, power ) s
INNER JOIN wands w ON s.code = w.code AND s.coins_needed = w.coins_needed AND s.power = w.power

2번에서 만난 오류

1) ON절 조건 설정
처음에 ON절에 code 컬럼이 동일해야한다는 조건 하나만 설정해줘서 오류가 발생했다. code, coins_needed, power 모든 컬럼에 대해서 각각 같아야한다는 조건을 넣어줬더니 해결됐다.

2) SELECT절 집계함수 참조
MIN(coins_needed) 에 alias 를 설정해주지 않고, 집계함수 형태 그대로 s.MIN(coins_needed) 를 넣어서 키 참조를 했더니 오류가 발생했다.

FROM(SELECT code, power, MIN(coins_needed)
	  FROM wands
	  GROUP BY code, power) s
INNER JOIN wands w ON s.code = w.code AND s.MIN(coins_needed) = w.MIN(coins_needed) AND s.power = w.power

다시 서브쿼리로 가서 집계함수에 alias 를 설정해주고 ( MIN(coins_needed) AS coins_needed ) 나머지 쿼리를 작성하니 정상 출력이 되었다.



3. age, is_evil 칼럼을 불러오기 위해서 wands_property 테이블과 조인
FROM (SELECT code, power, MIN(coins_needed) AS coins_needed
	  FROM wands
	  GROUP BY code, power) s
INNER JOIN wands w ON s.code = w.code AND s.coins_needed = w.coins_needed AND s.power = w.power
INNER JOIN wands_property p ON p.code = w.code
  1. is_evil=0 조건 추가
WHERE is_evil = 0
  1. ORDER BY 조건 추가
ORDER BY w.power DESC, p.age DESC
  1. 쿼리 출력 조건 id, age, coins_needed, and power of the wands
SELECT w.id, p.age, s.coins_needed, w.power

My Answer


SELECT w.id, p.age, s.coins_needed, w.power
FROM (SELECT code, power, MIN(coins_needed) AS coins_needed
	  FROM wands
	  GROUP BY code, power ) s
INNER JOIN wands w ON s.code = w.code AND s.coins_needed = w.coins_needed AND s.power = w.power
INNER JOIN wands_property p ON p.code = w.code
WHERE is_evil = 0
ORDER BY w.power DESC, p.age DESC
profile
study archive 👩‍💻

0개의 댓글

관련 채용 정보