[SQL] HAKERRANK - THE REPORT

2023. 3. 31. 13:40공부/SQL

https://www.hackerrank.com/challenges/the-report/ 

 

The Report | HackerRank

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

www.hackerrank.com

 

PROBLEM

 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.

 

NAME, GRADE, MARK의 칼럼들을 뽑아야하는데 이는 STUDENTS 테이블과 GRADES 테이블의 JOIN을 이용하면서 ORDER BY를 얼마나 잘 활용 할 수 있는지 물어보는 문제 같다.

 

JOIN 방법은 

SELECT S.NAME, G.GRADE, S.MARKS FROM STUDENTS S 
JOIN GRADES G
ON S.MARKS BETWEEN G.MIN_MARK AND G.MAX_MARK

두 테이블 사이에서 공통적으로 사용되는 MARK 컬럼을 BETWEEN을 사용해서 조인시켰다. 근데 여기서 몇가지 조건이 추가로 붙는데 목록화 시키면 다음과 같다.

 

CONDITION

  1.  GRADE가 8 보다 낮은 학생들의 이름은  NULL
  2. GRADE를 기준으로 내림차순 정렬과 동시에 8점 이상인 학생들의 GRADE가 동일 할 경우 학생들의 NAME 오름차순으로 정렬
  3. GRADE가 8 이하인 학생들의 정렬 규칙은 GRADE 내림차순 기준으로 하고, 그들의 GRADE가 같을 경우 MARK 오름차순으로 정렬할 것.

 

SOLUTION

1번 조건을 해결하려면 SELECT 절에 CASE를 사용하면 좋을 것같고, 나머지는 ORDER BY G.GRADE DESC, NAME ASC, MARKS ASC 이런식으로 하면 될 것 같다.

SELECT 
    CASE 
        WHEN G.GRADE<8 THEN NULL
        ELSE S.NAME
    END AS NAME,
    G.GRADE, 
    S.MARKS 
FROM STUDENTS S 
JOIN GRADES G
    ON S.MARKS BETWEEN G.MIN_MARK AND G.MAX_MARK
ORDER BY G.GRADE DESC, NAME ASC, MARKS ASC;

기초 공부를 열심히 하자

'공부 > SQL' 카테고리의 다른 글

[SQL] Hackerrank - Olivander's Inventory  (0) 2023.03.31
[SQL] HACKERRANK - TOP COMPETITORS  (0) 2023.03.31
[SQL] 문제풀이 TYPE OF TRIANGLE  (0) 2023.03.31
SQL - REGEXP  (0) 2023.03.30
SQL 기초 WHERE 절  (0) 2023.03.30