문제
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.
풀이
SELECT IF(g.grade >= 8, s.name, NULL) AS Name
,g.grade AS Grade
,s.marks AS Marks
FROM students AS s
LEFT JOIN grades AS g ON s.marks BETWEEN g.min_mark AND g.max_mark
ORDER BY g.grade DESC
,CASE WHEN g.grade IN (8,9,10) THEN s.name END ASC
,CASE WHEN g.grade BETWEEN 1 AND 7 THEN s.marks END ASC
<문제를 통해 새로 알게 된 점>
# ORDER BY에도 조건문 사용할 수 있음
# 컬럼명 똑바로 적자!
+) ORDER BY 다른 풀이
SELECT IF(g.grade >= 8, s.name, NULL) AS Name
,g.grade AS Grade
,s.marks AS Marks
FROM students AS s
LEFT JOIN grades AS g ON s.marks BETWEEN g.min_mark AND g.max_mark
ORDER BY g.grade DESC
, s.name
,s.marks
# 8-10등급은 이름을 같이 출력하기 때문에 grade -> name순으로 정렬
1-7등급은 이름을 출력하기 않고 NULL 처리. 따라서 실질적으로 grade -> marks순으로 정렬됨!
'SQL > HackerRank' 카테고리의 다른 글
| [SQL] HackerRank: Symmetric Pairs (0) | 2023.06.01 |
|---|---|
| [SQL] HackerRank: INNER JOIN 문제 (0) | 2023.05.31 |
| [SQL] HackerRank : Weather Observation Station 3 (0) | 2023.05.19 |
| [SQL] HackeRank : Weather Observation Station 11 (0) | 2023.05.19 |
| [SQL] HackerRank : The Blunder (0) | 2023.05.18 |