해당 문제는 HackerRank에서 사용한 문제이며 모든 테이블의 자료와 출처는 Hackerank임을 밝힙니다.
해당 글에서는 서브쿼리를 사용하여 푸는 문제로 난이도가 매우 낮은 문제입니다.
해당 문제 원본을 확인 하시려면 해당 사이트를 들어가시면 될 것 같습니다.
시작하겠습니다
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)고위력(high power) 및 고연령(age) 마법 지팡이를 구매하는 데 필요한 최소 골드 갤리온 수(coins_needed)를 기준으로 선택하는 것이 가장 좋은 방법이라고 결정합니다. 다음 조건에 따라 id, age,coins_needed, 그리고power를 출력하는 쿼리를 작성
해당 문제는 groupby와 ROW_NUMBER(윈도우 함수)를 적용하여 풀어보겠습니다.
추가로 age, power로 묶어준 뒤 최소 금액을 구해줍니다. 그리고 ROW_NUMBER를 사용할 때 partition by를 power, age로 나눠준 뒤 가격이 낮은 순으로 랭크를 부여한 뒤 1위인 지팡이만 가져오면 됩니다.
1. 각 age, power 별 최소 골드 요구하는 지팡이 찾기
select a.id, b.age, MIN(a.coins_needed) coins_needed, a.power
from Wands a
JOIN Wands_Property ON a.code = b.code
where b.is_evil = 0
group by a.id, b.age, a.power
각 age, power 그룹 별 최소 금액을 가지는 지팡이를 찾을 수 있습니다.
이제 해당 지표를 테이블로 설정하고 이어서 답을 찾아가 보겠습니다.
2. ROW_NUMBER 활용하여 랭크 부여
WITH CTE as (
select a.id, b.age, MIN(a.coins_needed) coins_needed, a.power
from Wands a
JOIN Wands_Property b ON a.code = b.code
where b.is_evil = 0
group by a.id, b.age, a.power
)
select *
, ROW_NUMBER() OVER (partition by age, power order by coins_needed) rank
from CTE
맨 오른쪽에 power, age 같은 것 중 저렴한 순으로 랭크를 부여 해주었습니다.
이제 문제에서 요구하는 age, power 별로 최소 금액인 지팡이를 선별 할 수 있게 되었습니다.
3. rank가 1인 행만 가져오고 ORDER BY로 정렬
WITH CTE as (
select a.id, b.age, MIN(a.coins_needed) coins_needed, a.power
from Wands a
JOIN Wands_Property b ON a.code = b.code
where b.is_evil = 0
group by a.id, b.age, a.power
)
select t.id, t.age, t.coins_needed, t.power
from (
select *
, ROW_NUMBER() OVER (partition by age, power order by coins_needed) rank
from CTE
) t
where t.rank = 1
order by t.power DESC, t.age DESC;
이렇게 where 절을 사용하여 각 값들에서 rank가 1인 값을 가져와주면 age, power 별 최소 금액인 값만 가져오게 됩니다. 그리고 order by를 통해 내림차순 정렬을 해주게 되면 답이 되게 됩니다.
이상으로 Hacker Rank 문제 풀이를 마치도록 하겠습니다.
728x90
'Data Analyst > SQL' 카테고리의 다른 글
[SQL] HackerRank 문제 풀기 (SQL Project Planning) (0) | 2025.01.13 |
---|---|
[SQL] HackerRank 문제 풀기 (Contest Leaderboard) (0) | 2025.01.11 |
[SQL] HackerRank 문제 풀기 (Weather Observation Station 15) (1) | 2024.11.15 |
[SQL] Programmers 문제 풀기(자동차 대여 기록 별 대여 금액 구하기) (1) | 2024.11.14 |
[SQL] Programmers 문제 풀기(5월 식품들의 총매출 조회하기) (3) | 2024.11.13 |