-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_joins.sql
More file actions
executable file
·89 lines (69 loc) · 2.38 KB
/
basic_joins.sql
File metadata and controls
executable file
·89 lines (69 loc) · 2.38 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Database that holds the records of students, their papers and their grades.
*/
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100)
);
CREATE TABLE papers(
title VARCHAR (255),
grade INT,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(id)
);
-----------------------------------------------------------------------
-----------------------------------------------------------------------
/*
1. Print the first name, paper title and corresponding grades
of the students that have at least one paper.
*/
SELECT first_name, title, grade FROM students
JOIN papers
ON students.id = papers.student_id;
-----------------------------------------------------------------------
-----------------------------------------------------------------------
/*
2. Print the first name, paper title and corresponding grades
of all students (if a student has no paper, print NULL instead of the
title and the grade).
*/
SELECT first_name, title, grade FROM students
LEFT JOIN papers
ON students.id = papers.student_id;
-----------------------------------------------------------------------
-----------------------------------------------------------------------
/*
3. Print the first name, paper title and corresponding grades
of all students (if a student has no paper, print "MISSING" instead of the
title and the "0" as the grade).
*/
SELECT first_name,
IFNULL(title,"MISSING"),
IFNULL(grade,0)
FROM students
LEFT JOIN papers
ON students.id = papers.student_id;
-----------------------------------------------------------------------
-----------------------------------------------------------------------
/*
4. Print for each student their first name and their average grade.
*/
SELECT first_name, AVG(IFNULL(grade,0)) AS average FROM students
LEFT JOIN papers
ON students.id = papers.student_id
GROUP BY first_name;
-----------------------------------------------------------------------
-----------------------------------------------------------------------
/*
4. Print for each student their first name, their average grade and
the passing status ("PASSING" if average >= 75, "NOT PASSING" else).
*/
SELECT first_name,
AVG(IFNULL(grade,0)) AS average,
CASE WHEN AVG(IFNULL(grade,0)) >= 75 THEN "PASSING"
ELSE "FAILING"
END AS "passing_status"
FROM students
LEFT JOIN papers
ON students.id = papers.student_id
GROUP BY first_namesudo;