코딩테스트연습(SQL)
Ollivander's Inventory / HackerRank, SQL, MSS SQL Server
LearnerToRunner
2023. 2. 20. 23:17
문제
source: HackerRank
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 != code2 and age1 != age2.
제출답안(MySQL)
-- id, age, coins, power
-- power DESC, age DESC
WITH inv AS (SELECT id, w.code, age, power, coins_needed
FROM wands AS w
JOIN (SELECT * FROM wands_property WHERE is_evil = 0)AS p
ON w.code = p.code),
inv_min AS (SELECT code, age, power, MIN(coins_needed) AS coins_needed
FROM inv
GROUP BY code, age, power)
SELECT id, i.age, i.coins_needed, i.power
FROM inv AS i JOIN inv_min AS m
ON i.code = m.code AND i.age = m.age AND i.power = m.power AND i.coins_needed = m.coins_needed
ORDER BY 4 DESC, 2 DESC
풀이(MS SQL Server)
더보기
Wands 와 Wands_property 테이블 조인한 서브쿼리 만들기
WITH inv AS (SELECT id, w.code, age, power, coins_needed
FROM wands AS w
JOIN (SELECT * FROM wands_property WHERE is_evil = 0)AS p
ON w.code = p.code),
코드, 나이, 파워별로 그룹화하여 각 그룹별 완드의 최소값을 구하는 서브쿼리
inv_min AS (SELECT code, age, power, MIN(coins_needed) AS coins_needed
FROM inv
GROUP BY code, age, power)
inv_min의 코드, 나이, 파워, 가격이 똑같은 값의 id, age, coins_needed, power 불러오기
SELECT id, i.age, i.coins_needed, i.power
FROM inv AS i JOIN inv_min AS m
ON i.code = m.code AND i.age = m.age AND i.power = m.power AND i.coins_needed = m.coins_needed
ORDER BY 4 DESC, 2 DESC
문제 바로가기(MS SQL Server)
728x90