๐ก ๋ฌธ์ ๋งํฌ
https://www.hackerrank.com/challenges/harry-potter-and-wands/problem?isFullScreen=true
์์ฝํ๋ฉด
SELECT D.ID, AB.AGE, D.COINS_NEEDED, AB.POWER
FROM(
SELECT A.POWER, B.AGE, MIN(A.COINS_NEEDED) MIN_COINS
FROM WANDS A
JOIN WANDS_PROPERTY B ON A.CODE=B.CODE
GROUP BY 1,2) AB
LEFT JOIN WANDS_PROPERTY C ON AB.AGE = C.AGE
LEFT JOIN WANDS D ON C.CODE=D.CODE
WHERE D.COINS_NEEDED = AB.MIN_COINS
AND C.IS_EVIL=0
ORDER BY 4 DESC, 2 DESC
;
SELECT A.POWER, B.AGE, MIN(A.COINS_NEEDED) MIN_COINS
FROM WANDS A
JOIN WANDS_PROPERTY B ON A.CODE=B.CODE
GROUP BY 1,2
์ฌ๊ธฐ๊น์ง๋ power, age๋ณ ์ต์ coins_needed ๊ฐ์ด ์ ์ถ๋ ฅ๋๋ค.
๋ฌธ์ ์์ age์ code๊ฐ one-one ๊ด๊ณ๋ผ๊ณ ์ฃผ์ด์ก์ผ๋ left join์ ์ฐจ๋ก๋๋ก ํ๋๋ฐ ๊ฒฐ๊ณผ๋ก power, age ๋ณ ์ค๋ณต ํ์ด ์๊ฒผ๋ค.
-- ์คํจํ ๋ต์
SELECT D.ID, AB.AGE, AB.MIN_COINS, AB.POWER
FROM(
SELECT A.POWER, B.AGE, MIN(A.COINS_NEEDED) MIN_COINS
FROM WANDS A
JOIN WANDS_PROPERTY B ON A.CODE=B.CODE
GROUP BY 1,2) AB
LEFT JOIN WANDS_PROPERTY C ON AB.AGE = C.AGE
LEFT JOIN WANDS D ON C.CODE=D.CODE
WHERE C.IS_EVIL=0
ORDER BY 4 DESC, 2 DESC
;
๊ฒฐ๊ตญ SELECT ๋ฌธ์์ AB.MIN_COINS ๋์ D.COINS_NEEDED๋ก ์์ ํ๊ณ ์กฐ๊ฑด๋ฌธ์ผ๋ก WHERE D.COINS_NEEDED = AB.MIN_COINS
๋ฅผ ์ถ๊ฐํ๋ ์ ๋๋ก ๋์๊ฐ๋ค.
LEFT JOIN์ ์๋ชป ์ดํดํ ํ์ด์๋ค. LEFT JOIN์
1) ์ผ์ชฝ ํ
์ด๋ธ์ ๋ชจ๋ ๋ ์ฝ๋๋ฅผ ๋ฆฌํดํ๊ณ
2) ์ค๋ฅธ์ชฝ์ ๋ ์ฝ๋ ์ค ์ผ์ชฝ ๋ ์ฝ๋์ ์ผ์นํ๋ ๊ฒฝ์ฐ๋ง ์ฑ์์ง ์ํ๋ก ๋ฆฌํด๋๋ค.
์ฌ๊ธฐ์ ์ผ์ชฝ ๋ ์ฝ๋๊ฐ (POWER, AGE) ๊ทธ๋ฃน๋ณ ์ต์ coin ๋ ์ฝ๋๊ฐ 1๊ฐ์ด์ง๋ง ์ค๋ฅธ์ชฝ ํ
์ด๋ธ๋ค์๋ (POWER, AGE)์ ํด๋นํ๋ ๋ ์ฝ๋๊ฐ ์ฌ๋ฌ๊ฐ์ด๋ค. ๋ฐ๋ผ์ ์ค๋ณตํ์ด ์๊ธฐ๋ ๊ฒ์ด๋ค.
๋์ ์กฐ๊ฑด๋ฌธ์ ์ด์ฉํ์ฌ (POWER, AGE)๋ณ ์ต์ COIN ๊ฐ์๋ฅผ ์ฐพ๋ ๋ฐฉ๋ฒ์ผ๋ก ๋ ๊น๋ํ ํ์ด๋ฅผ ์ฐพ์๋ค.
์ถ์ฒ : https://techblog-history-younghunjo1.tistory.com/165
SELECT A.ID, B.AGE, A.COINS_NEEDED, A.POWER
FROM WANDS A
JOIN WANDS_PROPERTY B ON A.CODE = B.CODE
WHERE B.IS_EVIL = 0
AND A.COINS_NEEDED = (
SELECT MIN(COINS_NEEDED)
FROM WANDS W1
INNER JOIN WANDS_PROPERTY P1 ON W1.CODE = P1.CODE
WHERE P1.IS_EVIL = 0
AND W1.POWER = A.POWER
AND P1.AGE = B.AGE
)
ORDER BY 4 DESC, 2 DESC
;
์๋ธ ์ฟผ๋ฆฌ์ WHERE ๊ตฌ๋ฌธ์์ ๋ฉ์ธ ์ฟผ๋ฆฌ์ ์นผ๋ผ์ ์ด์ฉํ๋ ์์๋ ์ฒ์ ๋ดค๋๋ฐ ํจ์ฌ ๊น๋ํ ๊ฒ ๊ฐ๋ค.
WHERE A.COINS_NEEDED = (์๋ธ์ฟผ๋ฆฌ)
ํ์