HAZEL

[서브쿼리] hackerrank : Contest Leaderboard 본문

DATA ANALYSIS/SQL

[서브쿼리] hackerrank : Contest Leaderboard

Rmsid01 2021. 11. 17. 23:51

 

>> 문제

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.

 

-> 해커의 총점은 모든 도전에 대한 최대 점수의 합입니다.

내림차순으로 정렬된 해커의 해커 ID, 이름, 총점을 출력하는 쿼리를 작성하십시오.

조건 :

1. 두 명 이상의 해커가 동일한 총점을 얻은 경우 해커 ID 오름차순으로 결과를 정렬합니다.

2. 결과에서 총 점수가 인 모든 해커를 제외합니다. 

3. total_score는 높은 점수대로, hacker_id는 낮은 순서대로 정렬. 0은 제외 

 

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

 

 

>> 문제 풀이

서브쿼리, GROUP BY를 사용하였다.

나는 LEFT JOIN을 사용하였는데, 문제 풀이에서는 inner join을 사용하였다. 이 문제에선 결과는 같았다.

SELECT hc.hacker_id, hc.name, sum(sub.sc) total_score
FROM (
    SELECT hacker_id, challenge_id, max(score) sc
    FROM Submissions
    GROUP BY hacker_id, challenge_id
    ) sub
    LEFT JOIN Hackers hc ON hc.hacker_id = sub.hacker_id 
GROUP BY sub.hacker_id, hc.name
HAVING total_score != 0
ORDER BY sum(sub.sc) desc, hc.hacker_id

 

 

https://www.hackerrank.com/challenges/contest-leaderboard/problem