the_report.md (3219B)
# The Report
[Link](https://www.hackerrank.com/challenges/the-report/problem)
Tables:
```sql
CREATE TABLE Students (ID INT, Name VARCHAR(255), Marks INT, PRIMARY KEY(ID)) ENGINE=InnoDB;
CREATE TABLE Grades (Grade INT, Min_Mark INT, Max_Mark INT, PRIMARY KEY(Grade)) ENGINE=InnoDB;
```
Data:
```sql
INSERT INTO test.Students (ID,Name,Marks) VALUES
(1,'Britney',95),
(2,'Heraldo',94),
(3,'Julia',96),
(4,'Kristeen',100),
(5,'Stuart',99),
(6,'Amina',89),
(7,'Christene',88),
(8,'Salma',81),
(9,'Samantha',87),
(10,'Scarlet',80),
(11,'Vivek',84),
(12,'Aamina',77),
(13,'Belvet',78),
(14,'Paige',74),
(15,'Priya',76),
(16,'Priyanka',77),
(17,'Anna',64),
(18,'Azamat',66),
(19,'Tracey',55),
(20,'Kim',34),
(21,'George',24);
```
```sql
INSERT INTO test.Grades (Grade,Min_Mark,Max_Mark) VALUES
(1,0,9),
(2,10,19),
(3,20,29),
(4,30,39),
(5,40,49),
(6,50,59),
(7,60,69),
(8,70,79),
(9,80,89),
(10,90,100);
```
The problem statement:
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.
Solution
```sql
MariaDB [test]> SELECT
-> CASE
-> WHEN s.Marks REGEXP '(7[0-9])|(8[0-9])|(9[0-9])|(100)' THEN s.Name
-> ELSE NULL
-> END AS Name,
-> CASE
-> WHEN s.Marks REGEXP '^([0-9])$' THEN 1
-> WHEN s.Marks REGEXP '^(1[0-9])$' THEN 2
-> WHEN s.Marks REGEXP '^(2[0-9])$' THEN 3
-> WHEN s.Marks REGEXP '^(3[0-9])$' THEN 4
-> WHEN s.Marks REGEXP '^(4[0-9])$' THEN 5
-> WHEN s.Marks REGEXP '^(5[0-9])$' THEN 6
-> WHEN s.Marks REGEXP '^(6[0-9])$' THEN 7
-> WHEN s.Marks REGEXP '^(7[0-9])$' THEN 8
-> WHEN s.Marks REGEXP '^(8[0-9])$' THEN 9
-> WHEN s.Marks REGEXP '^(9[0-9])|(100)$' THEN 10
-> ELSE 0
-> END AS Grade, s.Marks FROM Students s ORDER BY Grade DESC, Name ASC, s.Marks ASC;
+-----------+-------+-------+
| Name | Grade | Marks |
+-----------+-------+-------+
| Britney | 10 | 95 |
| Heraldo | 10 | 94 |
| Julia | 10 | 96 |
| Kristeen | 10 | 100 |
| Stuart | 10 | 99 |
| Amina | 9 | 89 |
| Christene | 9 | 88 |
| Salma | 9 | 81 |
| Samantha | 9 | 87 |
| Scarlet | 9 | 80 |
| Vivek | 9 | 84 |
| Aamina | 8 | 77 |
| Belvet | 8 | 78 |
| Paige | 8 | 74 |
| Priya | 8 | 76 |
| Priyanka | 8 | 77 |
| NULL | 7 | 64 |
| NULL | 7 | 66 |
| NULL | 6 | 55 |
| NULL | 4 | 34 |
| NULL | 3 | 24 |
+-----------+-------+-------+
21 rows in set (0.000 sec)
```