문제
You did such a great job helping Julia with her last coding contest challenge that she wants you to work on this one, too!
The total score of a hacker is the sum of their maximum scores for all of the challenges. Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id. Exclude all hackers with a total score of from your result.
SELECT H.hacker_id, name, SUM(m_score)
FROM Hackers H
JOIN (
SELECT hacker_id, challenge_id, MAX(score) AS m_score
FROM Submissions
GROUP BY hacker_id, challenge_id
) S ON S.hacker_id = H.hacker_id
GROUP BY H.hacker_id, name
HAVING SUM(m_score) > 0
ORDER BY SUM(m_score) DESC, H.hacker_id
이것이 정답쿼리다.
내가 쓴 기존 코드는 이렇다
SELECT H.Hacker_id, H.name, SUM(DISTINCT score)
FROM Hackers H JOIN Submissions S ON H.hacker_id = S.hacker_id
WHERE score =
(
SELECT MAX(S2.score)
FROM Submissions S2
WHERE S.hacker_id = S2.hacker_id AND S.challenge_id = S2.challenge_id
GROUP BY S2.hacker_id, S2.challenge_id
)
GROUP BY Hacker_id, H.name
HAVING SUM(DISTINCT score) != 0
ORDER BY SUM(DISTINCT score) DESC, H.Hacker_id ASC;
이렇게 고치면 안됩니까?
이 쿼리는 여전히 문제가 있을 수 있습니다. 연관 서브쿼리에서 GROUP BY S2.hacker_id, S2.challenge_id는 불필요합니다. 서브쿼리에서 WHERE S.hacker_id = S2.hacker_id AND S.challenge_id = S2.challenge_id 조건이 이미 특정 해커-챌린지 조합만 필터링하고 있기 때문입니다.
또한 SUM(DISTINCT score)를 사용하면 같은 점수를 가진 다른 챌린지의 점수가 한 번만 계산될 수 있어 정확한 총점을 구하지 못할 수 있습니다. 예를 들어, 한 해커가 두 개의 다른 챌린지에서 각각 100점을 받았다면, 이 점수는 한 번만 합산됩니다.
<2025년 5월 3일 복습>
이 문제에서 주의 할점은 제출한 모든 챌린지의 합계가 아니라. 챌린지별 최대점수의 합계다. 이점을 유의하자
'MYSQL > HakerRank_Medium' 카테고리의 다른 글
Placements 과 Join (0) | 2025.04.22 |
---|---|
SQL Project Planning과 Islands and Gaps 패턴 (0) | 2025.04.21 |
Challenges 와 WITH 절 (0) | 2025.04.18 |
Ollivander's Inventory와 서브쿼리 (0) | 2025.04.18 |
Top Competitors (0) | 2025.04.17 |