본문 바로가기
데이터/SQL 문제풀이

HackerRank SQL - Contest Leaderboard

by 찌노오 2023. 1. 31.

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.

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. 

Problem

hacker_id, name, hacker의 각 challenges 중에서 가장 높은 값의 합을 추출하라.

단, hackers의 점수합은 내림차순으로 정렬하고 같은 점수를 받은 hacker가 있다면 hacker_id로 정렬하라.

만약 총 점수합이 0인 hacker는 제외하라.


Answer1

SELECT S.hacker_id, H.name, SUM(S.score)
FROM Submissions S LEFT JOIN Hackers H ON H.hacker_id = S.hacker_id
WHERE S.submission_id in (SELECT TEMP_S.submission_id
                            FROM (SELECT S.submission_id
                                        ,ROW_NUMBER() OVER(PARTITION BY S.hacker_id, S.challenge_id 
                                                               ORDER BY S.score DESC) rnum
                                      FROM Submissions S
                                  ) TEMP_S
                           WHERE rnum = 1
                         )
GROUP BY S.hacker_id, H.name HAVING SUM(S.score) != 0
ORDER BY SUM(S.score) DESC, hacker_id;

각 hacker, challenge의 최대값의 submission_id를 where절 조건으로 넣었다.

그 이외 조건은 저번에 풀었던 풀이와 유사하다.

2023.01.29 - [데이터/SQL 문제풀이] - HackerRank SQL - Ollivander's Inventory

 

 


How to solve

문제가 뭔가 비슷한 것 같다.

그래서 별로 어렵지 않게 접근했다.

 

row_number함수를 이용해 각 challenges, hacker별로 최대 점수의 submission_id값을 추출한다.

SELECT TEMP_S.submission_id
  FROM (SELECT S.submission_id
               ,ROW_NUMBER() OVER(PARTITION BY S.hacker_id, S.challenge_id 
                                      ORDER BY S.score DESC) rnum
        FROM Submissions S
        ) TEMP_S
WHERE rnum = 1

 

나머지는 그냥 문제대로 따라가면 되는데, 총합이 0인 hacker를 제외하는 조건을 잊으면 안된다.

아래와 같이 메인쿼리의 마지막에 having절로 붙여주었다.

 

GROUP BY S.hacker_id, H.name HAVING SUM(S.score) != 0

 

 

 

 

반응형

댓글