[SQL][HackerRank]The Report

Yewon Kimยท2021๋…„ 12์›” 12์ผ

SQL

๋ชฉ๋ก ๋ณด๊ธฐ
4/6
post-thumbnail

๐Ÿ”Š๋ณธ ํฌ์ŠคํŒ…์—์„œ ์‚ฌ์šฉ๋˜๋Š” ํ…Œ์ด๋ธ”์˜ ์ž๋ฃŒ์™€ ์ถœ์ฒ˜๋Š” HackerRank ์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.
https://www.hackerrank.com/challenges/the-report/problem?isFullScreen=false


๐ŸŽˆ์กฐ๊ฑด

Ketty gives Eve a task to generate a report containing three columns: Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (8-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their grades in descending order. If there is more than one student with the same grade (1-7) assigned to them, order those particular students by their marks in ascending order.

Ketty๋Š” Eve์—๊ฒŒ Name, Grade, Mark 3๊ฐœ์˜ ์—ด์„ ํฌํ•จํ•˜๋Š” ๋ ˆํฌํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ž‘์—…์„ ์ค€๋‹ค.

  1. Ketty๋Š” Grade 8๋ณด๋‹ค ๋‚ฎ์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ํ•™์ƒ๋“ค์˜ ์ด๋ฆ„์€ ์›ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๊ทธ๋ฆฌ๊ณ  Grade๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ์ž‘์„ฑํ•ด์•ผํ•œ๋‹ค.

  2. ๋™์ผํ•œ ๋“ฑ๊ธ‰(Grade 8-10)์˜ ํ•™์ƒ์ด ๋‘ ๋ช… ์ด์ƒ ์žˆ๋Š” ๊ฒฝ์šฐ, ํ•ด๋‹น ํ•™์ƒ์˜ ์ด๋ฆ„์„ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.

  3. Grade๊ฐ€ 8๋ณด๋‹ค ๋‚ฎ์€ ๊ฒฝ์šฐ, ํ•ด๋‹น ํ•™์ƒ์˜ ์ด๋ฆ„์„ NULL๋กœ ํ‘œ์‹œํ•˜๊ณ  ํ•™์ƒ๋“ค์˜ ์ ์ˆ˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ์ž‘์„ฑํ•œ๋‹ค. ๋งŒ์•ฝ ๋™์ผํ•œ ๋“ฑ๊ธ‰(Grade 1-7)์˜ ํ•™์ƒ์ด ๋‘ ๋ช… ์ด์ƒ ์žˆ๋Š” ๊ฒฝ์šฐ, ํ•ด๋‹น ํ•™์ƒ์˜ marks๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.
    (Grade<8์ธ ํ•™์ƒ๋“ค์€ ์ด๋ฆ„์ด NULL๋กœ ํ†ต์ผ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— marks๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์ด๋‹ค.)

SELECT IF(Grades.Grade<8, NULL, Students.Name), Grades.Grade, Students.Marks
FROM Students
INNER JOIN Grades
ON Students.Marks BETWEEN Min_Mark AND Max_Mark
ORDER BY Grades.Grade DESC, Students.Name ASC, Students.Marks ASC;

๐ŸŽˆ๋ฌธ์ œํ•ด๊ฒฐ์„ ์œ„ํ•œ ์•„์ด๋””์–ด

  • IF๋ฌธ์„ ์ด์šฉํ•ด Grade 8๋ณด๋‹ค ๋‚ฎ์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ํ•™์ƒ๊ณผ ๋†’์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ํ•™์ƒ์œผ๋กœ ๋‚˜๋ˆ„์–ด ์ƒ๊ฐํ•œ๋‹ค.(CASE๋ฌธ์œผ๋กœ ๋Œ€์ฒด ๊ฐ€๋Šฅ)
SELECT CASE WHEN Grades.Grade<8 THEN NULL ELSE Students.Name END AS name, Grades.Grade, Students.Marks
FROM Students
INNER JOIN Grades
ON Students.Marks BETWEEN Min_Mark AND Max_Mark
ORDER BY Grades.Grade DESC, Students.Name ASC, Students.Marks ASC;

0๊ฐœ์˜ ๋Œ“๊ธ€