Approach
Relational aggregation
For Find Top Scoring Students II, the query transforms and combines relational rows, then filters or aggregates them into the requested result.
- Identify the source rows and join keys.
- Apply filters before aggregation when possible.
- Group, rank, or project the final columns required by the result.
Code notes
- 40 lines of SQL from the credited upstream file 3188.sql.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Review join cardinality, grouping keys, and available indexes when estimating query cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1WITH2 MandatoryMajors AS (3 SELECT major, COUNT(course_id) AS course_count4 FROM Courses5 WHERE mandatory = 'Yes'6 GROUP BY 17 ),8 StudentsMetadata AS (9 SELECT10 Students.student_id,11 Students.major,12 SUM(13 Students.major = Courses.major14 AND Courses.mandatory = 'YES'15 AND Enrollments.grade = 'A'16 ) AS mandatory_grade_a_count,17 SUM(18 Students.major = Courses.major19 AND Courses.mandatory = 'No'20 ) AS elective_count,21 ROUND(22 SUM(Enrollments.GPA * Courses.credits) / SUM(Courses.credits),23 124 ) AS avg_gpa25 FROM Students26 INNER JOIN Enrollments27 USING (student_id)28 INNER JOIN Courses29 USING (course_id)30 GROUP BY 131 )32SELECT StudentsMetadata.student_id33FROM StudentsMetadata34INNER JOIN MandatoryMajors35 ON (36 StudentsMetadata.major = MandatoryMajors.major37 AND StudentsMetadata.mandatory_grade_a_count = MandatoryMajors.course_count)38WHERE StudentsMetadata.avg_gpa >= 2.5 AND StudentsMetadata.elective_count >= 239ORDER BY 1;40