MySQL 해커랭크 | Top Competitors (HAVING절 사용)

    728x90

     

    문제

    https://www.hackerrank.com/challenges/full-score/problem?isFullScreen=true

     

    Top Competitors | HackerRank

    Query a list of top-scoring hackers.

    www.hackerrank.com

    • Write a query to print the respective hacker_id and name of hackers who achieved full scores for more than one challenge. 
    • Order your output in descending order by the total number of challenges in which the hacker earned a full score
    • If more than one hacker received full scores in same number of challenges, then sort them by ascending hacker_id.

     

    테이블 

    Hackers 테이블 Difficulty 테이블 Challenges 테이블 Submissions 테이블

     

    풀이과정

    1
    2
    3
    4
    SELECT hacker_id, name
    FROM Hackers
    WHERE challenge_id가 하나라도 있고 and score 가 풀스코어인 경우
    ORDER BY 해커가 풀스코어를 받은 챌린지 총 횟수 내림차순 , 이게 같은 경우엔 hacker_id 오름차순
    cs
     

    # 정답

    • 처음에 생각했던 것처럼 WEHRE절에 challenge_id가 하나라도 있는 경우를 조건으로 주진 못했음
      • 하지만 s.score가 d.score와 같아지게 함으로써 풀스코어를 받은 경우를 추려냄
        • s.score : 각 해커들의 제출 결과에 대한 점수
        • d.score : 난이도에 따른 제출 시 받을 수 있는 풀스코어
    • 해커 아이디와, 해커 이름으로 그룹을 만들고,
      그 안에서 HAVING절을 이용해 challenge_id가 하나라도 있는 경우를 조건으로 줌
    • 문제에서 요구한 대로 정렬 조건을 주면 끝!
    1
    2
    3
    4
    5
    6
    7
    8
    9
    SELECT h.hacker_id, h.name
    FROM Hackers h
    INNER JOIN Submissions s ON h.hacker_id = s.hacker_id
    INNER JOIN Challenges c ON s.challenge_id = c.challenge_id
    INNER JOIN Difficulty d ON c.difficulty_level = d.difficulty_level
    WHERE s.score = d.score 
    GROUP BY h.hacker_id, h.name
    HAVING COUNT(c.challenge_id) > 1
    ORDER BY COUNT(c.challenge_id) DESC, h.hacker_id
    cs

    728x90

    댓글