๐๋ณธ ํฌ์คํ
์์ ์ฌ์ฉ๋๋ ํ
์ด๋ธ์ ์๋ฃ์ ์ถ์ฒ๋ HackerRank ์์ ๋ฐํ๋๋ค.
https://www.hackerrank.com/challenges/harry-potter-and-wands/problem?isFullScreen=false
๐๋ฌธ์ ํ์ด
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.
ํด๋ฆฌํฌํฐ์ ์น๊ตฌ๋ค์ ์ฐฐ๋ฆฌ์ ์ค๋๋๊ณ ๋ถ์
์ง ์งํก์ด๋ฅผ ๊ต์ฒดํ๊ธฐ ์ํด ๋ก ๊ณผ ์ฌ๋ฆฌ๋ฒค๋ ์งํก์ด ๊ฐ๊ฒ๋ฅผ ๋ฐฉ๋ฌธํ๋ค.
ํค๋ฅด๋ฏธ์จ๋๋ ์งํก์ด๋ฅผ ๊ณ ๋ฅด๋ ์ต์ ์ ๋ฐฉ๋ฒ์ผ๋ก์ non-evil ์งํก์ด์ด๋ฉด์ ๋์ power์ age ํน์ฑ์ ๊ฐ๋ ์งํก์ด๋ฅผ ์ฌ๊ธฐ ์ํด ํ์ํ ์ต์ํ์ ๋(gold galleons)์ ๊ณ ๋ฅด๋ ๋ฐฉ๋ฒ์ ์ ์ํ๋ค. ์ด ๋ฐฉ๋ฒ์ ์ ์ฉํ์ ๋, ๋ก ์ด ๊ด์ฌ์์ด ํ ๋งํ ์งํก์ด์ id, age, coins_needed, power ๊ฐ๋ค์ ์ถ๋ ฅํด๋ผ. ์ด ๋ 1์ฐจ์ ์ผ๋ก ์ ๋ ฌ ๊ธฐ์ค์ power ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํ๋ฉฐ, ๋์ผํ power ๊ฐ์ด ์์ ๋๋ age ๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํด๋ผ.
(SELECT code, MIN(coins_needed) AS coins_needed, power
FROM Wands
GROUP BY code, power) AS M
์ด๋, code์ power๋ฅผ Groupingํ์ฌ ์ต์ ๊ธ์ก์ ์ถ๋ ฅํ๋๋ฐ id๊ฐ ํฌํจ๋์ด ์์ ๊ฒฝ์ฐ ์ค๋ฅ๊ฐ ๋ฐ์ํ๊ธฐ ๋๋ฌธ์ id๋ฅผ ๋บ ์ํ๋ก GROUP BY๋ฅผ ํด์ผํ๋ค.
๐ ํด๋น ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ ์ด์ ๋ ๋ฐ๋ก GROUP BY๊ฐ ํ๊ณ ์ถ์ "๋ฐ์ดํฐ์ ๊ทธ๋ฃนํ"๋ฅผ ํ์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ด๋ค. ์ฆ, ํ์ฌ ์ฟผ๋ฆฌ๋ฌธ์ด ๊ทธ๋ฃนํ๋ฅผ ํ ์ ์๋ ์ํ๋ผ๋ ์ด์ผ๊ธฐ์ด๋ค.
(SELECT code, MIN(coins_needed) AS coins_needed, power
FROM Wands
GROUP BY code, power) AS M
INNER JOIN Wands AS W ON M.code=W.code AND M.power=W.power AND M.coins_needed=W.coins_needed
(SELECT code, MIN(coins_needed) AS coins_needed, power
FROM Wands
GROUP BY code, power) AS M
INNER JOIN Wands AS W ON M.code=W.code AND M.power=W.power AND M.coins_needed=W.coins_needed
INNER JOIN Wands_Property AS P ON P.code=W.code
WHERE P.is_evil=0
ORDER BY W.power DESC, P.age DESC
SELECT W.id, P.age, W.coins_needed, W.power
SELECT W.id, P.age, W.coins_needed, W.power
FROM (SELECT code, MIN(coins_needed) AS coins_needed, power
FROM Wands
GROUP BY code, power) AS M
INNER JOIN Wands AS W ON M.code=W.code AND M.power=W.power AND M.coins_needed=W.coins_needed
INNER JOIN Wands_Property AS P ON P.code=W.code
WHERE P.is_evil=0
ORDER BY W.power DESC, P.age DESC;
๐์๊ฒฌ
์ด ๋ฌธ์ ๋ฅผ ๋ค์ ๋ง์ ์๊ฐ์ด ์์๋์๊ณ , ๋์๊ฒ ์ด๋ ต๊ฒ ๋๊ปด์ง ๋ฌธ์ ์ด๋ค. ๊ณผ์ 1์์ id๋ฅผ ํฌํจํ์์ ๊ฒฝ์ฐ, GROUP BY ์ค๋ฅ๊ฐ ์ ๋ฐ์ํ๋์ง์ ๋ํ ์ ํํ ์ด์ ๋ฅผ ๋ชฐ๋์๊ธฐ ๋๋ฌธ์ ๋ฌธ์ ๋ฅผ ํธ๋ ๊ณผ์ ์์ ๋ง์ด ํค๋งธ๋ค. GROUP BY ์ค๋ฅ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ๊ณผ์ 2์ฒ๋ผ join์ ์ฌ์ฉํ๋ฉด ๋๋ค๋ผ๋ ์ฌ์ค์ ์๊ฒ๋์๋ค.