-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise 09 - Joins.sql
More file actions
68 lines (51 loc) · 1.8 KB
/
Exercise 09 - Joins.sql
File metadata and controls
68 lines (51 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
-- Exercise 9 - Joins
-- create tables shown in udemy course
CREATE TABLE students(
id INT AUTO_INCREMENT,
first_name VARCHAR(50),
PRIMARY KEY (id)
);
CREATE TABLE papers (
title VARCHAR(255),
grade INT,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(id)
);
-- insert the given data
INSERT INTO students (first_name) VALUES
('Caleb'), ('Samantha'), ('Raj'), ('Carlos'), ('Lisa');
INSERT INTO papers (student_id, title, grade ) VALUES
(1, 'My First Book Report', 60),
(1, 'My Second Book Report', 75),
(2, 'Russian Lit Through The Ages', 94),
(2, 'De Montaigne and The Art of The Essay', 98),
(4, 'Borges and Magical Realism', 89);
-- print name title and grade
SELECT first_name, title, grade
FROM students s
JOIN papers p ON s.id = p.student_id
ORDER BY grade DESC;
-- print name title and grade event with students who havent written anything
SELECT first_name, title, grade
FROM students s
LEFT JOIN papers p ON s.id = p.student_id;
-- if no paper exists it should show the value null as missing and the grade as 0
SELECT first_name, IFNULL(title, 'MISSING'), IFNULL(grade, 0)
FROM students s
LEFT JOIN papers p ON s.id = p.student_id;
-- get the average grade of each student
SELECT first_name, AVG(IFNULL(grade, 0)) AS average_grade
FROM students s
LEFT JOIN papers p ON s.id = p.student_id
GROUP BY first_name
ORDER BY average_grade DESC;
-- get the average grade of each student and if the avg is over 75 they pass the semester
SELECT first_name, AVG(IFNULL(grade, 0)) AS average_grade,
CASE
WHEN AVG(IFNULL(grade, 0)) > 75 THEN 'PASSING'
ELSE 'FAILING'
END AS passing_test
FROM students s
LEFT JOIN papers p ON s.id = p.student_id
GROUP BY first_name
ORDER BY average_grade DESC;