์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[HackerRank] The Report (SQL/JOIN)

PROGRAMMING/Database

by koharin 2021. 2. 6. 11:58

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

 

 

๐Ÿ’ป Oracle ์ œ์ถœ์ฝ”๋“œ


SELECT (CASE WHEN GRADES.GRADE < 8 THEN 'NULL' ELSE STUDENTS.NAME END), GRADES.GRADE, STUDENTS.MARKS
FROM STUDENTS, GRADES
WHERE STUDENTS.MARKS BETWEEN GRADES.MIN_MARK AND GRADES.MAX_MARK
ORDER BY GRADES.GRADE DESC, NAME ASC;
  • CASE WHEN  ~ THEN ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ GRADES.GRADE < 8์ธ ๊ฒฝ์šฐ ์ด๋ฆ„์„ NULL์œผ๋กœ, ์•„๋‹ˆ๋ฉด ์ด๋ฆ„ ๊ทธ๋Œ€๋กœ(STUDENTS.NAME) ์กฐํšŒํ•œ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ์„ฑ์ , ์ ์ˆ˜๋ฅผ ์กฐํšŒํ•˜๋Š”๋ฐ ์„ฑ์ ์€ GRADES ํ…Œ์ด๋ธ”์— ์žˆ์œผ๋ฏ€๋กœ GRADES.GRADE๋กœ, ์ ์ˆ˜๋Š” STUDENTS ํ…Œ์ด๋ธ”์— ์žˆ์œผ๋ฏ€๋กœ STUDENTS.MARKS๋กœ ์กฐํšŒํ•œ๋‹ค.
  • JOIN์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ํ…Œ์ด๋ธ” 2๊ฐœ์—์„œ ๊ฐ€์ ธ์˜ค๋„๋ก FROM๋ฌธ์—์„œ STUDENTS, GRADES๋ฅผ ์คฌ๋‹ค.
  • WHERE๋ฌธ์—์„œ BETWEEN ~ AND๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฐ STUDENTS.MARKS๋งˆ๋‹ค ๋ฒ”์œ„ ๋‚ด์˜ GRADE๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค.
  • ORDER BY
    • 8~10 ์„ฑ์ ์ธ ๊ฒฝ์šฐ, GRADE๊ฐ€ ๋†’์€ ์„ฑ์  ์ˆœ(DESC), ์„ฑ์ ์ด ๊ฐ™์œผ๋ฉด NAME์ด ASC ์ˆœ์ด๋‹ค.
    • 1~7 ์„ฑ์ ์ธ ๊ฒฝ์šฐ, GRADE๊ฐ€ ๋†’์€ ์„ฑ์  ์ˆœ(DESC), ์„ฑ์ ์ด ๊ฐ™์œผ๋ฉด MARKS๊ฐ€ ASC ์ˆœ์ด๋‹ค. (์ด๋ฆ„์ด ์—†์œผ๋ฏ€๋กœ)

 

์ด ์ฝ”๋“œ์—์„œ๋Š” JOIN์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์ง€๋งŒ, JOIN์„ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ORACLE ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

SELECT (CASE WHEN B.GRADE < 8 THEN 'NULL' ELSE A.NAME END), B.GRADE, A.MARKS
FROM STUDENTS A
JOIN GRADES B
ON A.MARKS BETWEEN B.MIN_MARK AND B.MAX_MARK
ORDER BY B.GRADE DESC, A.NAME, A.MARKS;
  • SELECT๋ฌธ์€ ๋˜‘๊ฐ™๊ณ , JOIN์„ ์“ฐ๋Š”๋ฐ, WHERE๋ฌธ ๋Œ€์‹  ON์„ ์“ฐ๋ฉด ๋œ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ์ฒซ ๋ฒˆ์งธ ์ฝ”๋“œ์—์„œ๋Š” ๊ทธ๋ƒฅ ๋์ง€๋งŒ, ๋” ์ •ํ™•ํ•˜๊ฒŒ๋Š” ORDER BY์—์„œ NAME์ด NULL์ธ ์„ฑ์  1-7์˜ ๊ฒฝ์šฐ, ์„ฑ์ ์ด ๊ฐ™์œผ๋ฉด MARKS๋ฅผ ASC ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋ฏ€๋กœ ์ •๋ ฌ ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•ด์คฌ๋‹ค.

 

 

๐Ÿ–จ ๊ฒฐ๊ณผ


Britney 10 95 
Heraldo 10 94 
Julia 10 96 
Kristeen 10 100 
Stuart 10 99 
Amina 9 89 
Christene 9 88 
Salma 9 81 
Samantha 9 87 
Scarlet 9 80
Vivek 9 84 
Aamina 8 77 
Belvet 8 78 
Paige 8 74 
Priya 8 76 
Priyanka 8 77  
NULL 7 64 
NULL 7 66 
NULL 6 55 
NULL 4 34 

728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ