문제
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.
Input Format
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
https://www.hackerrank.com/challenges/challenges/problem?isFullScreen=true
예시
Hackers Table:
Challenges Table:
21283 Angela 6
88255 Patrick 5
96196 Lisa 1
문제 풀이
SELECT hackers.hacker_id
, hackers.name
, COUNT(*) AS challenges_created
FROM Challenges
INNER JOIN Hackers ON Challenges.hacker_id = Hackers.hacker_id
GROUP BY hackers.hacker_id, hackers.name
HAVING challenges_created = (SELECT MAX(Challenges_created)
FROM (
SELECT hacker_id
,COUNT(*) AS challenges_created
FROM Challenges
GROUP BY hacker_id) sub)
OR challenges_created IN (SELECT challenges_created
FROM (
SELECT hacker_id
,COUNT(*) AS challenges_created
FROM Challenges
GROUP BY hacker_id) sub
GROUP BY challenges_created
HAVING COUNT(*) = 1)
ORDER BY challenges_created DESC, hacker_id
WITH counter AS(
SELECT hackers.hacker_id
, hackers.name
, COUNT(*) AS challenges_created
FROM Challenges
INNER JOIN Hackers ON Challenges.hacker_id = Hackers.hacker_id
GROUP BY hackers.hacker_id, hackers.name
)
SELECT counter.hacker_id
, counter.name
, counter.challenges_created
FROM counter
WHERE challenges_created = (SELECT MAX(challenges_created) FROM counter)
OR challenges_created IN (SELECT challenges_created
FROM counter
GROUP BY challenges_created
HAVING COUNT(*) = 1)
ORDER BY counter.challenges_created DESC, counter.hacker_id
SQL을 독학하시는 분들에게 도움이 되길 바라며,
혹 더 좋은 방법이 있거나 오류가 있다면 편하게 말씀 부탁드립니다.