본문 바로가기
문제풀이/SQL(My sql)

[문제풀이] Hacker Rank - THE REPORT

by kime2 2024. 6. 11.
출처
 

The Report | HackerRank

Write a query to generate a report containing three columns: Name, Grade and Mark.

www.hackerrank.com

 

 

문제

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 테이블2. Grades

문제에 대한 해석

출력 : Name, Grade and Mark.
조건 : grade 8초과, 이름 -> 'NULL' 

정렬 : grade 내림차순
8-10 > 이름 순
1-7 > 점수 오름차순

 

 

풀이(MYSQL)

-- 정답1 : grade를 조건문을 통해 입력
with tmp as (
    SELECT 
    name,
    case when marks between 0 and 9 then 1
        when marks between 10 and 19 then 2
        when marks between 20 and 29 then 3
        when marks between 30 and 39 then 4
        when marks between 40 and 49 then 5
        when marks between 50 and 59 then 6
        when marks between 60 and 69 then 7
        when marks between 70 and 79 then 8
        when marks between 80 and 89 then 9
        when marks between 90 and 100 then 10 end as grade,
        marks
FROM Students
order by grade)
select 
    if(grade<8, NULL, name) as name
    , grade
    , marks
from tmp
order by grade desc, name, marks

-- 정답2. : grade를 join을 통해 입력
select 
    if(Grades.grade < 8, Null, name ) as name
    , Grades.grade
    , Students.marks
from Students join Grades
on Students.marks between Grades.min_mark and Grades.max_mark
order by Grades.grade desc, Students.name, Students.marks

 

작동순서

💡SQL 실행 순서는 From -> Where -> Group by -> Having -> Select -> Order by ->결과반환

 

  1. FROM 절: Students.marksStudents.marks 와 Grades.max_mark의 사이에 있는 경우 Students와 Students을 이너조인 
  2. SELECT 절: Grades.grade가 8초과일 경우 NULL을 출력하고 아니면 name컬럼을 가져와서 name컬럼에 저장, grade, marks 조회
  3. ORDER BY 절: grade의 내림차순으로 하고, 같은 grade면 이름의 오름차순, 같은 이름이면 mark의 오름차순으로 정렬하라

우선 grade가 큰 것부터 정렬을 하는데,

점수가 같다면

grade가 8초과일 경우 이름 순


8이하일 경우 점수 오름차순 -> 8이하의 경우 이름이 NULL이므로 이름순으로 정렬이 되어도 반영 X

모두 같은 이름인 null 이므로 이름정렬 후 marks로 정렬

다른사람 풀이

SELECT Name,Grade,Marks 
FROM Students,Grades 
WHERE Marks BETWEEN Min_Mark AND Max_Mark and Grade>=8 
ORDER BY Grade desc,Name;
-- Grade>=8인 경우 Grade desc,Name으로 정렬

SELECT null,Grade,Marks 
FROM Students,Grades 
WHERE Marks BETWEEN Min_Mark AND Max_Mark and Grade<8 
ORDER BY Grade desc,Name,Marks;
-- Grade<8인 경우 Grade desc,Name,Marks으로 정렬

배운점

만약 8이하의 등급의 이름이 NULL이 아니었다면, 정렬을 별도로 한위 union으로 합쳐야 할듯