본문 바로가기
배우기/SQL

HackerRank - Contest Leaderboard(조인, 서브쿼리)_MySQL

by 인사잘해 2022. 4. 21.

안녕하세요!

 

해커랭크의 Contest Leaderboard 문제입니다.

 

- 문제

총 점수는 참가자 별로 각 도전에서 얻은 최고 점수를 합산한 것이다.

hacker_id, name, total score 를 조회하고 total score를 기준으로 내림차순 정렬한다.

만약 두 명 이상의 참가자가 동점일 경우 hacker_id를 기준으로 오름차순 정렬한다.

총 점수가 0인 참가자는 제외한다.

 

- 테이블

- 쿼리

1. 조인과 서브쿼리 사용

select h.hacker_id, name, sum(max_score) total_score
from hackers h
  inner join (select hacker_id, challenge_id, max(score) max_score
                from submissions
                where score != 0
                group by 1, 2) m
  on h.hacker_id = m.hacker_id
group by 1, 2
order by 3 desc, 1

1) hacker_id 별로 각각의 challenge_id 의 최고점을 구한다.

2) where 절에 score 가 0 이 아닌 조건을 건다.

3) m 으로 명명한 테이블로 만들어 hackers 테이블과 hacker_id 기준으로 조인한다.

4) hacker_id, name 을 group by 하고 max_score 의 합계를 구한다.

5) 정렬은 total_score 의 내림차 순, hacker_id 의 오름차 순으로 한다.

 

 

 

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

댓글