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.
Sample Input
Sample Output
Maria 10 99
Jane 9 81
Julia 9 88
Scarlet 8 78
NULL 7 63
NULL 7 68
Note
Print "NULL" as the name if the grade is less than 8.
Explanation
Consider the following table with the grades assigned to the students:
So, the following students got 8, 9 or 10 grades:
- Maria (grade 10)
- Jane (grade 9)
- Julia (grade 9)
- Scarlet (grade 8)
두 개의 테이블이 주어집니다.
- Students 테이블에는 학생의 ID, 이름(Name), 성적(Marks)이 저장되어 있습니다.
- Grades 테이블은 특정 점수 구간(Min_Mark ~ Max_Mark)에 해당하는 Grade를 정의합니다.
Ketty는 다음과 같은 조건으로 보고서를 생성하려 합니다.
- Grade가 8 이상인 학생들만 이름을 보여줍니다.
- Grade가 8 미만인 경우, 이름은 'NULL'로 출력합니다.
- 전체 결과는 Grade 내림차순으로 정렬합니다.
- Grade가 같을 경우:
- Grade ≥ 8: 이름 오름차순 정렬
- Grade < 8: 점수(Marks) 오름차순 정렬
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,
CASE
WHEN G.Grade >= 8 THEN S.Name
ELSE NULL
END ASC,
CASE
WHEN G.Grade < 8 THEN S.Marks
ELSE NULL
END ASC;
- JOIN: 점수(Marks)가 Grade 범위에 속하는지 확인
- CASE WHEN: Grade < 8일 경우 이름 대신 'NULL' 출력
- ORDER BY에서 조건 분기:
- Grade 내림차순
- Grade ≥ 8 → 이름 기준 정렬
- Grade < 8 → 점수 기준 정렬
'Computer Science > SQL' 카테고리의 다른 글
SQL | HackerRank Ollivander’s Inventory (0) | 2025.06.21 |
---|---|
SQL | HackerRank 코딩 대회에서 여러 문제를 만점 받은 참가자 찾기 (0) | 2025.06.20 |
SQL | HackerRank ROW_NUMBER()와 COUNT(*) OVER()를 활용하여 중앙값(Median) 구하기 (0) | 2025.06.18 |
SQL | HackerRank 평균 오차 구하기 (Replace) (0) | 2025.06.17 |
SQL | HackerRank 이진 트리 노드 유형(Root, Inner, Leaf) 구분하는 쿼리 (0) | 2025.06.16 |