Skip to content

Commit 50db492

Browse files
authored
Merge pull request #229 from Latsan/main
using multiple subqueries in one table
2 parents 38175c0 + 206b9ce commit 50db492

File tree

6 files changed

+73
-0
lines changed

6 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
SELECT s.name,
2+
(SELECT e.exam_date
3+
FROM Exam e
4+
WHERE e.student_id = s.id
5+
AND e.exam_date >= ALL (SELECT exam_date FROM Exam WHERE student_id = s.id)) AS last_exam_date,
6+
(SELECT c.name
7+
FROM Exam e
8+
JOIN Course c ON e.course_id = c.id
9+
WHERE e.student_id = s.id
10+
AND e.exam_date >= ALL (SELECT exam_date FROM Exam WHERE student_id = s.id)) AS last_exam_course,
11+
(SELECT COUNT(*)
12+
FROM Exam e
13+
WHERE e.student_id = s.id) AS total_exams
14+
FROM Student s;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
WITH RankedExams AS (
2+
SELECT
3+
e.student_id,
4+
c.name AS course_name,
5+
e.exam_date,
6+
ROW_NUMBER() OVER (PARTITION BY e.student_id ORDER BY e.exam_date DESC) AS rn,
7+
COUNT(*) OVER (PARTITION BY e.student_id) AS total_exams
8+
FROM Exam e
9+
JOIN Course c ON e.course_id = c.id
10+
)
11+
SELECT
12+
s.name,
13+
re.exam_date AS last_exam_date,
14+
re.course_name AS last_exam_course,
15+
re.total_exams
16+
FROM Student s
17+
LEFT JOIN RankedExams re ON s.id = re.student_id AND re.rn = 1;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
SELECT s.name,
2+
e.exam_date AS last_exam_date,
3+
c.name AS last_exam_course,
4+
(SELECT COUNT(*) FROM Exam WHERE student_id = s.id) AS total_exams
5+
FROM Student s
6+
LEFT JOIN Exam e ON s.id = e.student_id
7+
LEFT JOIN Course c ON e.course_id = c.id
8+
WHERE e.exam_date = (
9+
SELECT exam_date
10+
FROM Exam
11+
WHERE student_id = s.id
12+
AND exam_date >= ALL (SELECT exam_date FROM Exam WHERE student_id = s.id)
13+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
SELECT s.name, exam_counts.course_name, exam_counts.exam_count
2+
FROM Student s
3+
JOIN (
4+
SELECT e.student_id, c.name AS course_name, COUNT(*) AS exam_count
5+
FROM Exam e
6+
JOIN Course c ON e.course_id = c.id
7+
GROUP BY e.student_id, c.name
8+
HAVING COUNT(*) = (
9+
SELECT MAX(exam_count)
10+
FROM (
11+
SELECT student_id, course_id, COUNT(*) AS exam_count
12+
FROM Exam
13+
GROUP BY student_id, course_id
14+
) max_counts
15+
WHERE max_counts.student_id = e.student_id
16+
)
17+
) exam_counts ON s.id = exam_counts.student_id;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
SELECT s.name,
2+
(SELECT COUNT(*)
3+
FROM Exam e
4+
WHERE e.student_id = s.id) AS exam_count
5+
FROM Student s;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
SELECT s.name
2+
FROM Student s
3+
WHERE 5 < (
4+
SELECT COUNT(*)
5+
FROM Exam e
6+
WHERE e.student_id = s.id
7+
);

0 commit comments

Comments
 (0)