[Hacker Rank_MySQL]문제 풀이#Challenges 본문

IT/코테문제

[Hacker Rank_MySQL]문제 풀이#Challenges

호랑구야 2022. 3. 1. 09:00

SQL > Basic Join > Challenges

 

Challenges | HackerRank

Print the total number of challenges created by hackers.

www.hackerrank.com

 

Julia asked her students to create some coding challenges. Write a query to print the hacker_idname, and the total number of challenges created by each student. Sort your results by the total number of challenges in descending order. If more than one student created the same number of challenges, then sort the result by hacker_id. If more than one student created the same number of challenges and the count is less than the maximum number of challenges created, then exclude those students from the result.

빨간 글씨는 내가 문제를 풀 때 중요하다고 생각한 부분이다.

두가지 조건이 존재한다.

도전의 수가 최대일 때는 전부 출력하지만, 도전의 수가 최대보다 작으면서 그 수만큼 시도한 학생의 수가 여러 명일 경우에는 리스트에서 제외해야한다.

따라서 도전의 수가 그 최대치와 같을 때와, 도전의 수가 유일하게 존재할 때를 각각 구해야한다.

처음에는 WHERE 구문을 이용해서 구현하려다가 디스커션에서 HAVING을 이용한 것을 보고 참고했다.

SELECT H.HACKER_ID, H.NAME, COUNT(C.HACKER_ID) AS CNT
FROM HACKERS H
JOIN CHALLENGES C
ON C.HACKER_ID = H.HACKER_ID
GROUP BY H.HACKER_ID, H.NAME
HAVING
    (CNT = (SELECT MAX(X.CN)
          FROM (SELECT COUNT(HACKER_ID) CN
               FROM CHALLENGES
               GROUP BY HACKER_ID)X))
OR
    (CNT IN (SELECT Y.CN
             FROM (SELECT COUNT(HACKER_ID) CN
                   FROM CHALLENGES
                   GROUP BY HACKER_ID)Y
            GROUP BY Y.CN
            HAVING COUNT(Y.CN) = 1))
ORDER BY CNT DESC, H.HACKER_ID ASC
반응형
Comments