[TIL] MySQL TIL Day 3

1 ๋ถ„ ์†Œ์š”

๐ŸŸก [HackerRank] Contest Leaderboard

https://www.hackerrank.com/challenges/contest-leaderboard/problem?isFullScreen=true

Trial

์ด ๋ฌธ์ œ๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. sql ์ดˆ์งœ๋ผ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์ œ๋Œ€๋กœ ์จ๋ณธ ์ ์ด ์—†์–ด ๋‚œํ•ญ์„ ๊ฒช์—ˆ๋‹ค..์ฒ˜์Œ์—๋Š” GROUP BY๋กœ Max์™€ Sum์„ ๋™์‹œ์— ์ˆ˜ํ–‰ํ•˜๋ ค ํ–ˆ์ง€๋งŒ (๋‹น์—ฐํžˆ) ์‹คํŒจํ–ˆ๋‹ค. ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” ์‰ฝ๊ฒŒ ๋งํ•˜๋ฉด SQL๋ฌธ ์•ˆ์— ์žˆ๋Š” ๋˜ ๋‹ค๋ฅธ SQL ๋ฌธ์ด๋‹ค. ์„œ๋ธŒ์ฟผ๋ฆฌ์— ๋Œ€ํ•œ ์„ค๋ช…์€ ์ด ํฌ์ŠคํŒ…์— ์ž˜ ์ •๋ฆฌ๋˜์–ด ์žˆ์–ด ์ฐธ๊ณ ํ•˜๊ธฐ ์ข‹์•˜๋‹ค.

Solution

์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋จผ์ € hacker_id, challenge_id๋กœ ๊ทธ๋ฃนํ™”ํ•˜์—ฌ score์˜ max๋ฅผ ๋ฝ‘๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•œ ํ›„, ๊ธฐ์กด์˜ hacker table๊ณผ ์กฐ์ธํ•ด์•ผ ํ•œ๋‹ค.

Step 1

FROM ์ ˆ์— ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. Submission table์—์„œ hacker_id, challenge_id๋กœ ๊ทธ๋ฃนํ™”(Group by) ํ›„ ๊ฐ ๊ทธ๋ฃน๋ณ„ max score๋ฅผ ์ถ”์ถœํ•œ๋‹ค. ํ•ด๋‹น ์„œ๋ธŒ์ฟผ๋ฆฌ๋Š” s๋กœ ๋ช…๋ช…ํ•œ๋‹ค.(ALIAS)

Step 2

Step 1์—์„œ ์ƒ์„ฑํ•œ ์„œ๋ธŒ์ฟผ๋ฆฌ์™€ Hackers table๋ฅผ JOIN ํ•œ๋‹ค. ์ด ๋•Œ hacker_id๋ฅผ ๊ธฐ์ค€์œผ๋กœ JOIN!

Step 3

์ด์ œ ๊ฐ hacker_id ๋ณ„ total score๋ฅผ ๊ณ„์‚ฐํ•˜๊ธฐ ์œ„ํ•ด GROUP BY๋ฅผ ๋‹ค์‹œ ํ•œ๋‹ค. Output์—์„œ hacker_id, name, total score ์นผ๋Ÿผ์„ ํฌํ•จํ•  ๊ฒƒ์ด๋ฏ€๋กœ GROUP BY hacker_id, name์œผ๋กœ ์ง€์ •ํ•ด์ค€๋‹ค. ๊ฐ total_score์€ SUM(score)์„ ์ด์šฉํ•˜์—ฌ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

Step 4

๋ฌธ์ œ์—์„œ ์ œ์‹œํ•œ ์กฐ๊ฑด์— ๋”ฐ๋ผ total score์ด 0๋ณด๋‹ค ํฐ ๋ฐ์ดํ„ฐ๋งŒ ์„ ํƒํ•˜๊ณ , total score ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ, hacker_id ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.

SELECT h.hacker_id, h.name, SUM(score) AS total
FROM (SELECT hacker_id, challenge_id, MAX(score) AS score
      FROM submissions GROUP BY hacker_id, challenge_id) AS s
JOIN hackers AS h ON h.hacker_id = s.hacker_id
GROUP BY h.hacker_id, h.name
HAVING total > 0
ORDER BY total DESC, hacker_id

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ