/////
Search
Duplicate

Top Competitors

태그
JOIN
한 번 더 체크

문제

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:
Sample Output
90411 Joe
SQL
복사

정답

SELECT H.hacker_id as hacker_id, MAX(H.name) as Name FROM Submissions S LEFT JOIN Hackers H ON S.hacker_id = H.hacker_id LEFT JOIN Challenges C ON S.challenge_id = C.challenge_id LEFT JOIN Difficulty D ON C.difficulty_level = D.difficulty_level WHERE S.score = D.score GROUP BY H.hacker_id HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC, hacker_id ;
SQL
복사

풀이

JOIN을 이용하여 푸는 문제이다.
우선 JOIN을 이용하여 Submission 테이블에 나머지 테이블을 붙였다.
FROM Submissions S LEFT JOIN Hackers H ON S.hacker_id = H.hacker_id LEFT JOIN Challenges C ON S.challenge_id = C.challenge_id LEFT JOIN Difficulty D ON C.difficulty_level = D.difficulty_level
SQL
복사
그 다음 Submission 테이블의 score와 Difficulty 테이블의 스코어가 같은 데이터만을 조회하였다. Difficulty 테이블의 스코어가 만점을 의미하고 Submission 스코어가 받은 점수를 의미하므로 둘이 같다면 만점을 받았다는 뜻이 된다. (그런데 문제에 오류가 있다. Submission 점수가 만점보다 높은 데이터들이 존재한다. 그래서 S.score >= D.score 로 풀면 틀렸다고 나온다..)
WHERE S.score = D.score
SQL
복사
그 다음 hacker_id로 그룹핑을 해서 id 별 횟수를 세어준다. 그리고 이를 이용하여 1 번 초과로 나오는 데이터를 조회한다.
GROUP BY H.hacker_id HAVING COUNT(*) > 1
SQL
복사
나머지는 조건에 따라 출력하면 된다.