본문 바로가기
[업무 지식]/MySQL

[MAX() over()] Challenges

by 에디터 윤슬 2024. 11. 29.

링크

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

 

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_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.

 

정답

with cte as (
    SELECT x.hacker_id as hacker_id,
            x.name as name,
            x.counter,
            MAX(x.counter) OVER () AS maxm, 
            COUNT(x.counter) OVER (PARTITION BY x.counter) AS countOfCounts
    FROM (
        SELECT h.hacker_id as hacker_id, h.name as name, COUNT(ch.challenge_id) AS counter
        FROM Hackers h
        JOIN Challenges ch ON h.hacker_id = ch.hacker_id
        GROUP BY h.hacker_id, h.name
    ) AS x
)
select hacker_id,
        name,
        counter
from cte
where counter = maxm or countOfCounts = 1
order by counter desc, hacker_id

새롭게 이해한 내용

  • MAX(column) over () : 최댓값 컬럼을 생성하여 모든 행에 추가할 수 있다.
  • COUNT(column) over(partition by column) : 값에 따라 갯수를 파악할 수 있다