This problem requires identifying students who consistently avoid scoring the highest or lowest in all exams they take. The solution leverages SQL's window functions for efficient ranking and aggregation.
Approach:
Ranking within Exams: The core idea is to rank each student's score within each exam. We use the RANK()
window function twice: once in ascending order (rk1
) and once in descending order (rk2
). RANK()
assigns the same rank to ties, which is crucial because we want to exclude students who tied for highest or lowest.
Joining with Student Table: The ranked results are joined with the Student
table to retrieve student names.
Aggregation and Filtering: We group the results by student_id
. The HAVING
clause filters out students where the sum of rk1 = 1
(highest score) and rk2 = 1
(lowest score) is 0. This ensures that a student only qualifies if they never achieved the highest or lowest rank in any exam. Finally, the results are ordered by student_id
.
MySQL Code:
WITH
T AS (
SELECT
student_id,
RANK() OVER (
PARTITION BY exam_id
ORDER BY score
) AS rk1,
RANK() OVER (
PARTITION BY exam_id
ORDER BY score DESC
) AS rk2
FROM Exam
)
SELECT student_id, student_name
FROM
T
JOIN Student USING (student_id)
GROUP BY 1
HAVING SUM(rk1 = 1) = 0 AND SUM(rk2 = 1) = 0
ORDER BY 1;
Time Complexity Analysis:
The time complexity is dominated by the window function operations (RANK()
). Window functions typically have a time complexity of O(N log N) in the worst case, where N is the number of rows in the Exam
table, due to the sorting involved. The subsequent GROUP BY
and HAVING
operations have a complexity of O(M log M) where M is the number of distinct students. Since M <= N, the overall time complexity is approximately O(N log N).
Space Complexity Analysis:
The space complexity depends on the intermediate result set generated by the CTE (T
). In the worst case, this CTE could hold a copy of the Exam
table, resulting in a space complexity of O(N). The space used for the final result set is at most O(M) which is smaller than O(N). Therefore, the overall space complexity is approximately O(N).