[HackerRank]Contest Leaderboard

SQL-쿼리테스트

목록 보기
15/21

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


Q)

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.

지난번 코딩 대회 챌린지에서 줄리아를 정말 잘 도와주셔서 이번 챌린지에서도 도와주셨으면 좋겠어요!
해커의 총 점수는 모든 챌린지의 최대 점수를 합산한 것입니다. 내림차순 점수 순으로 해커의 hacker_id, 이름, 총 점수를 출력하는 쿼리를 작성하세요. 두 명 이상의 해커가 동일한 총점을 획득한 경우, 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

A)

우선 문제에서 요구하는 사항은 다음과 같다.

  1. Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score

    hacker_id, name, total score 을 출력하고, score 를 기준으로 내림차순 정렬하여라.

  2. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id

    점수가 동일할 경우 hacker_id 를 기준으로 오름차순 정렬하여라.

  3. Exclude all hackers with a total score of 0 from your result.

    total score가 0 점인 hacker 는 제외하여라

우선 예시에서 주어진 것 처럼 hacker 가 동일한 challenges 를 시도했을 경우 더 높은 점수를 획득한 점수로 인정해주기 때문에 이를 구하는 쿼리를 먼저 작성하였다.

SELECT
    HACKER_ID,CHALLENGE_ID,MAX(SCORE) AS SCORE
FROM SUBMISSIONS
GROUP BY HACKER_ID,CHALLENGE_ID

이 후 한명의 hacker가 풀이한 challenge 의 총 점수의 합을 구하면 되기에 위 쿼리를 서브쿼리로 활용하여 아래와 같이 구할 수 있었다.

SELECT 
    H.HACKER_ID,H.NAME,SUM(S.SCORE) TOTAL_SCORE
FROM
(
    SELECT
        HACKER_ID,CHALLENGE_ID,MAX(SCORE) AS SCORE
    FROM SUBMISSIONS
    GROUP BY HACKER_ID,CHALLENGE_ID
)S
JOIN HACKERS H ON S.HACKER_ID = H.HACKER_ID
GROUP BY S.HACKER_ID,H.NAME
HAVING TOTAL_SCORE != 0
ORDER BY TOTAL_SCORE DESC, HACKER_ID;

이전 문제들과 달리 간단하게 해결할 수 있었던 이번 문제였다.

profile
살아남기 위해 끄적이는 블로그 : 생존법

0개의 댓글