Milky's note

[HackerRank](M) Top Competitors 본문

SQL/SQL 코딩 테스트-HackerRank

[HackerRank](M) Top Competitors

밀뿌 2022. 3. 31. 16:35

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

 

Top Competitors | HackerRank

Query a list of top-scoring hackers.

www.hackerrank.com

 

[문제]

Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! 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.


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.
     
  • Difficulty: The difficult_level is the level of difficulty of the challenge, and score is the score of the challenge for the difficulty level.
     
  • Challenges: The challenge_id is the id of the challenge, the hacker_id is the id of the hacker who created the challenge, and difficulty_level is the level of difficulty of the challenge.
     
  • 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 that the submission belongs to, and score is the score of the submission.
     

Sample Input

Hackers Table: 

 Difficulty Table: 

 Challenges Table: 

 Submissions Table: 

 

 

[답]

- mysql

select h.hacker_id, h.name from hackers h
join submissions s on h.hacker_id = s.hacker_id
join challenges c on s.challenge_id = c.challenge_id
inner join difficulty d on d.difficulty_level = c.difficulty_level
where d.score = s.score
group by h.hacker_id, h.name
having count(h.hacker_id) > 1
order by count(h.hacker_id) desc, h.hacker_id

먼저 문제를 요약해보면 

코딩 테스트 문제에서 2문제 이상 만점을 받은 사람들의 id와 이름을 출력하는데 정렬 순서는 만점이 많은 사람순으로 정렬하는데 만점의 수가 동일하다면 hacker_id의 오름차순으로 정렬을 하여라. 이다.

내가 생각해낸 방법은 이전 문제에서 알게된 다중 join으로 해결을 하고 싶었다.

그리하여 submissions과 challenges는 full join을 해주었고 난이도와 만점을 나타내는 difficulty는 리스트로 join을 해주기 위해 inner join을 사용하였다.

컬럼을 보고 조건으로 사용할 수 있는 컬럼들을 사용하여서 3개의 join을 추가해주었다.

그래서 difficulty 테이블의 만점과 사용자들이 맞은 점수가 같으면 그 사용자는 만점을 받으 것으로 생각한다. (d.score = s.score)

그리고 2번 이상의 만점을 받은 사람들을 추출해야하기 때문에 having절로 조건을 추가해주었다. having count(h.hacker_id) > 1

마지막으로 정렬을 하라고하는 순서대로 정렬을 해주었다 !!!

다중 join으로 문제를 푸니까 코드도 짧아지고 편리하다! 앞으로 자주 써먹어야지~~

Comments