Challenges | HackerRank
Print the total number of challenges created by hackers.
www.hackerrank.com
☑️ Challenges
[문제]
- 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.
- 학생별 총 챌린지수 집계하기
- 최대 챌린지 수를 가진 학생 제외하고, 같은 개수를 가진 학생이 있다면 결과에서 제외
- challenge 횟수 내림차,해커아이디 오름차 정렬
[문제 풀이]
내 코드
WITH sub AS ( -- 학생별 챌린지수 집계
SELECT c.hacker_id,h.name
,COUNT(DISTINCT c.challenge_id)AS cnts
FROM Challenges c
INNER JOIN hackers h ON c.hacker_id = h.hacker_id
GROUP BY c.hacker_id,h.name
)
SELECT hacker_id,name,cnts
FROM sub
WHERE cnts = (SELECT MAX(cnts) FROM sub ) -- 최다 챌린지수 생성자는 전부 출력
OR cnts IN (SELECT cnts
FROM sub
GROUP BY cnts
HAVING COUNT(DISTINCT hacker_id) =1
) -- 중복될경우는 제거
ORDER BY cnts DESC,hacker_id
수정 코드
이슈 및 해결 과정
- 내코드 아이디어 : 챌린지수 집계 CTE 생성후 , 최다 집계자 전부 or 중복된 챌린지수 제거하기 위한 where 절 필터링
- sub CTE : 해커아이디별 챌린지 수 집계
- 아우터쿼리
- where 서브쿼리 조건 1 : 집계 수가 CTE의 최대값이랑 같을때 전부 출력 ( 최다 집계자 all)
- where 서브쿼리 조건 2 : 집계수를 그룹바이 한 뒤 중복 값이 없는 것만 출력
피드백 한줄 포인트
- 필터링 조건이 복잡하게 구분되어 있을때, where 절 서브쿼리와 OR AND 연산자로 해결 가능
'SQL' 카테고리의 다른 글
코테준비 | 해커랭크 interviews (다중 테이블 join) (0) | 2025.02.06 |
---|---|
코테준비 | 해커랭크 SQL Project Planning / Placements (연속된 그룹 필터링/다중 JOIN) (0) | 2025.01.31 |
코테준비 | Second Highest Salary (의도적으로 null 값 출력하기) (0) | 2025.01.16 |
QCC | 4회차 코드 리뷰 & 피드백 (0) | 2025.01.16 |
코테 준비 | Group Sold Products By The Date(group_concat) (0) | 2025.01.15 |