[HackerRank] Challenges

당당·2023년 7월 20일
0

HackerRank

목록 보기
17/27

https://www.hackerrank.com/challenges/challenges/problem

📔문제

Julia asked her students to create some coding challenges. Write a query to print the hacker_id, name, 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.

The following tables contain challenge data:

  • Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker.

  • Challenges: The challenge_id is the id of the challenge, and hacker_id is the id of the student who created the challenge.


📝예시

Hackers Table:

Challenges Table:

21283 Angela 6
88255 Patrick 5
96196 Lisa 1

Hackers Table:

Challenges Table:

12299 Rose 6
34856 Angela 6
79345 Frank 4
80491 Patrick 3
81041 Lisa 1

For Sample Case 0, we can get the following details:

Students 5077 and 62743 both created 4 challenges, but the maximum number of challenges created is 6 so these students are excluded from the result.

For Sample Case 1, we can get the following details:

Students 12299 and 34856 both created challenges. Because is the maximum number of challenges created, these students are included in the result.


🧮분야

  • JOIN

📃SQL 코드

select hacker_id, b.name, cnt
from (select hacker_id, name, cnt,
     count(cnt) over (partition by cnt) rep,
      max(cnt) over() maxs
      from (select h.hacker_id, h.name, count(*) cnt
           from challenges c inner join hackers h
           on c.hacker_id=h.hacker_id
           group by h.hacker_id, h.name) a
      order by cnt desc, hacker_id)b
where rep=1 or cnt=maxs;

📰출력 결과


📂고찰

with절을 잘 모르기 때문에, 서브쿼리랑 집계함수를 이용했다.

각각이 만든 챌린지 수를 cnt로 저장하고, 그 cnt를 기준으로 만약 같은 cnt가 있으면, 즉 챌린지를 만든 개수가 같은 사람이 있는지를 테스트하는 rep을 지정해두고 최대 챌린지 수를 maxs에 저장해둔다.

그 다음, rep=1 이거나 챌린지수가 최대챌린지수인 것만 뽑는다.

profile
MySQL DBA 신입

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

너무 좋은 글이네요. 공유해주셔서 감사합니다.

답글 달기