[SQL] - 문제풀이 - HackerRank - Top Competitors

jonghyun.log·2022년 12월 6일
0

알고리즘-SQL

목록 보기
2/2
post-thumbnail

문제 링크

문제 조건

  • Write a query to print the respective
    hacker_id and name of hackers who achieved full scores for more than one challenge.

→ 2개 이상의 도전에서 만점 받은 해커들의 hacker_id 와 이름 출력

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

→ 만점받은 도전의 개수가 동일할 경우 hacker_id 로 오름차순으로 정렬

문제 해결

  1. 만점 달성 조건 : Submissions 테이블의 스코어와 Challenges 테이블 -> Difficulty 테이블 의 스코어와 같아야 만점 달성
  2. 두개 이상의 챌린지에서 만점을 받아야 함 : 만점 받은 챌린지 갯수 구하기 -> 1의 조건을 만족하는 챌린지의 개수를 가져와야하는데 어떻게..?

→ COUNT(Distinct 해커 이름) 을 통해 갯수를 카운트하고 갯수가 2 이상인 것만 출력 하기

일단 서브미션 테이블이 fk 모임이므로 서브미션으로 조회하고 join 으로 붙여주는 식으로 진행

서브미션 테이블에 해커, 챌린지, 디피컬티를 싹다 조인하고

“서브미션 스코어 = 디피컬티 스코어” ⇒ 만점


SELECT Ha.hacker_id, Ha.name
FROM Submissions Sub
	JOIN Hackers Ha ON Sub.hacker_id = Ha.hacker_id
	JOIN Challenges Ch ON Sub.challenge_id = Ch.challenge_id
	JOIN Difficulty Di ON Ch.difficulty_level = Di.difficulty_level
WHERE Sub.score = Di.score
GROUP BY Ha.hacker_id, Ha.name
HAVING COUNT(Ha.name) > 1
ORDER BY COUNT(Ha.name) DESC, Ha.hacker_id ASC

Ha.hacker_id, Ha.name 를 기준으로 데이터를 집계하고 출력해야하므로,

GROUP BY 를 Ha.hacker_id, Ha.name 로 해주었다.

0개의 댓글