본문 바로가기

Algorithm/MySQL

[해커랭크(HackerRank)] The Report (MySQL)

문제

You are given two tables: Students and Grades. Students contains three columns ID, Name and Marks.

Grades contains the following data:

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.

Write a query to help Eve.

  1. Students 테이블은 학생 정보, Grades 테이블은 점수 등급과 최소 점수, 최대 점수
  2. 8등급 미만의 학생들 이름 출력 X (너무하네 )
  3. 등급 별로 내림차순
  4. 같은 등급의 학생이 2 이상이면 학생들의 이름을 알파벳 순으로 출력
  5. 이름이 null일 때는 점수 순으로 출력
  6. 마지막으로, 8 미만의 등급인 학생들은 그들의 이름을 null 처리
  7. 출력할 항목은 이름 / 등급 / 점수 순으로

코드

1. 먼저 Students와 Grades의 테이블을 각각 확인하여 들어있는 데이터 조회

2. 학생들의 정보를 기준으로 등급을 조건에 맞게 넣어줘야 하기 때문에 INNER JOIN 사용

3. 조인 조건을 사용하려고 봤더니 학생들의 점수를 등급별 최대, 최소 점수 사이에 넣어줘야겠다 싶어 BETWEEN 사용
사실 모르고 했다가 조회해봤더니 되서 기분이 좋았다ㅋㅋㅋㅋㅋㅋㅋ

SELECT *
FROM Students s
     INNER JOIN Grades g ON s.marks Between g.min_mark and g.max_mark

s.id, s.name, s.marks, g.grade, g.min_mark, g.max_mark 순으로 출력

4. 등급은 내림차순으로 정렬, 다음 순서인 학생들의 이름은 알파벳순으로 정렬

SELECT *
FROM Students s
     INNER JOIN Grades g ON s.marks Between g.min_mark and g.max_mark
ORDER BY g.grade DESC, s.name

5. Ketty 등급이 8 미만인 학생들의 이름은 null 출력한다고 했으므로 (😭) case문으로 조건 걸어줌

SELECT CASE WHEN g.grade < 8 THEN NULL ELSE s.name END AS Name
FROM Students s
     INNER JOIN Grades g ON s.marks Between g.min_mark and g.max_mark
ORDER BY g.grade DESC, s.name

6. 이름 / 등급 / 점수 순으로 출력, 이름이 null일 때는 점수 순으로 출력해야하므로 order by에 점수 컬럼 추가

SELECT CASE WHEN g.grade < 8 THEN NULL ELSE s.name END AS Name
     , g.grade
     , s.marks
FROM Students s
     INNER JOIN Grades g ON s.marks Between g.min_mark and g.max_mark
ORDER BY g.grade DESC, s.name, s.marks

출처

반응형