https://www.hackerrank.com/challenges/the-report/problem?isFullScreen=true
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.
문제 상황을 요약해보자면 grade 8을 기준으로 더 낮은 경우와 높은 경우에 정렬 조건이 다르다.
Grade가 8 이상인 경우 Grade 내림차순, Name 오름차순 정렬을 하고
Grade가 7 이하인 경우 Grade 내림차순, Mark 오름차순 정렬을 해야한다.
결과적으로 7 이하인 경우 이름이 NULL로 가명처리되므로 구분되지 않기 때문에
Grade가 8 이상인 경우 Grade 내림차순, Name 오름차순 정렬을 하고 이후의 Mark 오름차순은 해도 문제가 되지 않는다.
Grade가 7 이하인 경우 Grade 내림차순, (Name 오름차순,) Mark 오름차순 정렬을 해도 마찬가지로 조건을 만족한다.
따라서 두 경우를 WHERE 절로 구분해서 작성하지 않고 한번에 처리한 쿼리는 아래와 같다.
SELECT CASE
WHEN g.GRade >= 8 THEN s.Name ELSE 'NULL'
END AS name
, g.Grade AS grade
, s.Marks AS mark
FROM Students AS s
INNER JOIN Grades AS g ON s.Marks BETWEEN g.Min_Mark AND g.Max_Mark
ORDER BY g.Grade DESC, s.Name, s.Marks
'SQL' 카테고리의 다른 글
[JOIN] LEFT JOIN 효과적으로 사용하기 (0) | 2024.02.18 |
---|---|
DISTINCT 대신 GROUP BY? (1) | 2024.02.10 |
[HackerRankSQL] Symmetric Pairs (0) | 2024.02.02 |
[HackerRank SQL] Top Earners (0) | 2024.01.21 |