본문 바로가기
SQL/MySQL

[MySQL] HackerRank - Contest Leaderboard 문제 풀이

by 취준생 져니 2024. 8. 28.

문제 사이트

아래 문제는 해커랭크에서 추출해온 문제입니다. 문제의 저작권은 해커랭크에 있으며 문제를 풀어보시려면 아래 링크를 클릭해주세요 🙂


 

Contest Leaderboard | HackerRank

Generate the contest leaderboard.

www.hackerrank.com

 

 

 

👉문제 설명

더보기
닫기

You did such a great job helping Julia with her last coding contest challenge that she wants you to work on this one, too!

The total score of a hacker is the sum of their maximum scores for all of the challenges. Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id. Exclude all hackers with a total score of  from your result.

 

🎙️
해커의 총 점수는 모든 도전 과제에 대한 최대 점수의 합이다. hacker_id, 이름 및 총 점수를 출력하는 쿼리를 작성하고 total_score 순으로 내림차순 정렬하라. 둘 이상의 해커가 동일한 총 점수를 달성한 경우 hacker_id를 오름차순으로 정렬하라. 총 점수가 0인 해커는 결과에서 제외

 

 

👉문제 풀이

해커별 챌린지에서 가장 높게 받은 점수들의 합을 구하는 비교적 간단한 문제

 

순서

1. hacker_id, challenge_id 별 가장 높게 받은 점수 출력

2. 점수들의 합 구하기

3. total_score > 0, 정렬조건 만족

 

 

 

 

 

👉문제 풀이 과정

1. hacker_id, challenge_id 별 가장 높게 받은 점수 출력, 서브쿼리 사용

select hacker_id, challenge_id, max(score) as max_score
from Submissions
group by hacker_id, challenge_id

 

 

 

2. 점수들의 합 구하기

select h.hacker_id, h.name, sum(s.max_score) as total_score
from Hackers h inner join (select hacker_id, challenge_id, max(score) as max_score
                            from Submissions
                            group by hacker_id, challenge_id) as s
on h.hacker_id = s.hacker_id
group by h.hacker_id, h.name

 

 

 

 

 

3. total_score > 0, 정렬조건 만족

select h.hacker_id, h.name, sum(s.max_score) as total_score
from Hackers h inner join (select hacker_id, challenge_id, max(score) as max_score
                            from Submissions
                            group by hacker_id, challenge_id) as s
on h.hacker_id = s.hacker_id
group by h.hacker_id, h.name
having total_score > 0
order by total_score desc, hacker_id

 

 

👉최종 답안

select h.hacker_id, h.name, sum(s.max_score) as total_score
from Hackers h inner join (select hacker_id, challenge_id, max(score) as max_score
                            from Submissions
                            group by hacker_id, challenge_id) as s
on h.hacker_id = s.hacker_id
group by h.hacker_id, h.name
having total_score > 0
order by total_score desc, hacker_id

 

 

 

👉고찰

window 함수를 사용해서 간단하게 하려고 했으나 hacker rank에서는 버전문제로 실행이 안됐음

두번째 group by에서 hacker_id로 묶으려고 하니 오류가 발생

-> hacker_id, name으로 같이 묶어주니 해결됨