링크
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.
정답
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) : 값에 따라 갯수를 파악할 수 있다
'[업무 지식] > MySQL' 카테고리의 다른 글
[recursive] Draw The Triangle (0) | 2024.12.12 |
---|---|
[날짜 그룹화] SQL Project Planning (0) | 2024.12.03 |
[row index] Weather Observation Station 20 (0) | 2024.11.25 |
[left, right] Weather Observation Station 8 (0) | 2024.11.19 |
[REGEXP] Find Users With Valid E-Mails (0) | 2024.11.18 |