MySQL 해커랭크 | Contest Leaderboard

    728x90

     

    문제

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

     

    Contest Leaderboard | HackerRank

    Generate the contest leaderboard.

    www.hackerrank.com

    • 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.

     

    테이블

    Hackers 테이블 Submissions 테이블

     

    풀이과정

    # 정답

    • 첫 번째 FROM절의 테이블에 서브쿼리를 넣었는데
      서브쿼리 내의 FROM절에도 서브쿼리를 넣었음 (갑분 마트료시카 쿼리문..)
      • 가장 높은 스코어의 합계를 구해야 하는데
        SUM(MAX(score)) 이런 식으로 중복 집계함수 사용이 안돼서 서브쿼리를 두 번 쓰게 됨
    • WHERE 조건절에 스코어가 0이 아니어야 한다는 조건을 준 뒤
    • ORDER BY절에서 정렬 조건을 주면 끝!
    1
    2
    3
    4
    5
    6
    7
    SELECT b.hacker_id, h.name, b.score
    FROM (SELECT a.hacker_id, SUM(max_s) score
          FROM (SELECT hacker_id, challenge_id, MAX(score) max_s FROM Submissions GROUP BY 12) a
          GROUP BY 1) b
    JOIN Hackers h ON h.hacker_id = b.hacker_id
    WHERE b.score > 0
    ORDER BY 3 DESC, 1
    cs

    728x90

    댓글