๐ก ๋ฌธ์ ๋งํฌ
https://www.hackerrank.com/challenges/challenges/problem?isFullScreen=true&h_r=next-challenge&h_v=zen
Hackers
Challenges
-- (1) total ๊ฐ์ด ์ต๋์ธ ํ์
SELECT H.HACKER_ID, H.NAME, B.TOTAL
FROM (
SELECT A.TOTAL, COUNT(A.TOTAL) TOTAL_COUNT
FROM (
SELECT HACKER_ID, COUNT(CHALLENGE_ID) TOTAL
FROM CHALLENGES
GROUP BY 1
) A
GROUP BY A.TOTAL
ORDER BY 1 DESC
LIMIT 1) B
JOIN (
SELECT HACKER_ID, COUNT(CHALLENGE_ID) TOTAL
FROM CHALLENGES
GROUP BY 1
) C ON B.TOTAL = C.TOTAL
JOIN HACKERS H ON H.HACKER_ID=C.HACKER_ID
ORDER BY 3 DESC, 1;
--- (2) total ๊ฐ์ด ์ ์ผํ ํ์
SELECT H.HACKER_ID, H.NAME, B.TOTAL
FROM (
SELECT A.TOTAL, COUNT(A.TOTAL) TOTAL_COUNT
FROM (
SELECT HACKER_ID, COUNT(CHALLENGE_ID) TOTAL
FROM CHALLENGES
GROUP BY 1
) A
GROUP BY A.TOTAL
HAVING TOTAL_COUNT = 1) B
JOIN (
SELECT HACKER_ID, COUNT(CHALLENGE_ID) TOTAL
FROM CHALLENGES
GROUP BY 1
) C ON B.TOTAL = C.TOTAL
JOIN HACKERS H ON H.HACKER_ID=C.HACKER_ID
ORDER BY 3 DESC, 1;
๐ก ์ถ์ฒ :
https://techblog-history-younghunjo1.tistory.com/157?category=962943
SELECT Hackers.hacker_id, Hackers.name, COUNT(*) AS challenges_created
FROM Hackers
INNER JOIN Challenges ON Hackers.hacker_id = Challenges.hacker_id
GROUP BY Hackers.hacker_id -- hacker id๊ฐ primary key์ญํ ์ ํ๋ค๋ฉด, name์ ๋นผ๋ ๋ ๊ฒ ๊ฐ๋ค.
HAVING challenges_created IN (SELECT sub2.challenges_created
FROM (SELECT hacker_id, COUNT(*) AS challenges_created
FROM Challenges
GROUP BY Challenges.hacker_id) sub2
GROUP BY sub2.challenges_created
HAVING COUNT(*) = 1)
OR challenges_created = (SELECT MAX(sub1.challenges_created)
FROM (SELECT COUNT(*) AS challenges_created
FROM Challenges
GROUP BY Challenges.hacker_id) sub1)
ORDER BY challenges_created DESC, Hackers.hacker_id
group by
๋ฅผ ์ฐ๊ณ having count(*)=1
์ผ๋ก ๋น๋์ ๋ํ ์กฐ๊ฑด๋ฌธ์ ๊ฑธ์๋ค.