Milky's note

[HackerRank](M) Contest Leaderboard 본문

SQL/SQL 코딩 테스트-HackerRank

[HackerRank](M) Contest Leaderboard

밀뿌 2022. 3. 30. 16:51

https://www.hackerrank.com/challenges/contest-leaderboard/problem?isFullScreen=true 

 

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  0 from your result.

Input Format

The following tables contain contest data:

  • Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker. 
  • Submissions: The submission_id is the id of the submission, hacker_id is the id of the hacker who made the submission, challenge_id is the id of the challenge for which the submission belongs to, and score is the score of the submission.
     

Sample Input

Hackers Table: 

Submissions Table: 

Sample Output

4071 Rose 191
74842 Lisa 174
84072 Bonnie 100
4806 Angela 89
26071 Frank 85
80305 Kimberly 67
49438 Patrick 43

Explanation

Hacker 4071 submitted solutions for challenges 19797 and 49593, so the total score = 95 + max(43, 96) = 191

Hacker 74842 submitted solutions for challenges 19797 and 63132, so the total score = max(98, 5) + 76 = 174

Hacker 84072 submitted solutions for challenges 49593 and 63132, so the total score = 100 + 0 = 100

The total scores for hackers 4806, 26071, 80305, and 49438 can be similarly calculated.

 

 

[답]

- mysql

select a.hacker_id, h.name, sum(a.mscore) total
from 
(select hacker_id, challenge_id, max(score) mscore
from submissions
group by hacker_id, challenge_id) a
join hackers h
on a.hacker_id = h.hacker_id
group by a.hacker_id, h.name
having total > 0
order by total desc, a.hacker_id

 

문제를 읽다가 조금 헷갈린 부분이 있어서 먼저 정리를 하려고 한다.

max 점수 구하는 부분인데 데이터를 잘 보면 challenge_id를 보면 알 수 있듯이 한 명이 여러번 코딩 테스트를 시도해서 그 중 제일 높은 값이 해당 문제에 대한 점수가 된다. 다음 표에서 예를 들었다. 

hacker_id challenge_id score
1111 10001 11
1111 10001 78
1111 10002 97

위와 같은 점수가 있을 때 hacker는 몇 번의 챌린지를 할 수 있고 같은 문제를 풀었을 때 점수는 가장 높은 값으로 선정한다.

따라서 해당 해커의 점수는 두번 푼 10001 문제에 대한 점수는 가장 높은 78점이고, 한 번 푼 10002에 대한 점수는 97점으로 두 점수의 합인 185점이 총점을 의미한다.

 

내가 생각한 문제푸는 순서는 먼저 group by를 통해서 hacker_id, challenge_id, score를 구해야한다.

그 뒤에 점수의 총점과 정렬, 0점이상인 점수만 추가 하는 등의 조건을 추가해준다.

이중 select 문을 사용하였고 그 안에 최대 점수 구하는 쿼리를 작성해주었다.

그리고 join을 통해서 문제에서 말하는 hacker의 이름을 출력해주어야 하고 해커의 아이디와 이름 별로 점수의 합을 나타내어야해서 group by를 해주고 0점 이상인 결과만 sum을 해주어야해서 having 절로 조건을 추가해주었다.

마지막으로 정렬은 먼저 점수가 높은 순서대로 진행하고 점수가 같다면 hacker_id의 오름차순으로 정렬을 해주면 된다 !!!!

 

Comments