-
leetcode - 1412. Find the Quiet Students in All ExamsSQL 문제풀이 2022. 9. 14. 19:01
난이도 : Hard
Table: Student
+---------------------+---------+ | Column Name | Type | +---------------------+---------+ | student_id | int | | student_name | varchar | +---------------------+---------+ student_id is the primary key for this table. student_name is the name of the student.
Table: Exam
+---------------+---------+ | Column Name | Type | +---------------+---------+ | exam_id | int | | student_id | int | | score | int | +---------------+---------+ (exam_id, student_id) is the primary key for this table. Each row of this table indicates that the student with student_id had a score points in the exam with id exam_id.
A quiet student is the one who took at least one exam and did not score the high or the low score.
Write an SQL query to report the students (student_id, student_name) being quiet in all exams. Do not return the student who has never taken any exam.
Return the result table ordered by student_id.
The query result format is in the following example.
Example 1:
Input: Student table: +-------------+---------------+ | student_id | student_name | +-------------+---------------+ | 1 | Daniel | | 2 | Jade | | 3 | Stella | | 4 | Jonathan | | 5 | Will | +-------------+---------------+ Exam table: +------------+--------------+-----------+ | exam_id | student_id | score | +------------+--------------+-----------+ | 10 | 1 | 70 | | 10 | 2 | 80 | | 10 | 3 | 90 | | 20 | 1 | 80 | | 30 | 1 | 70 | | 30 | 3 | 80 | | 30 | 4 | 90 | | 40 | 1 | 60 | | 40 | 2 | 70 | | 40 | 4 | 80 | +------------+--------------+-----------+ Output: +-------------+---------------+ | student_id | student_name | +-------------+---------------+ | 2 | Jade | +-------------+---------------+ Explanation: For exam 1: Student 1 and 3 hold the lowest and high scores respectively. For exam 2: Student 1 hold both highest and lowest score. For exam 3 and 4: Studnet 1 and 4 hold the lowest and high scores respectively. Student 2 and 5 have never got the highest or lowest in any of the exams. Since student 5 is not taking any exam, he is excluded from the result. So, we only return the information of Student 2.
WITH sub AS ( SELECT * , DENSE_RANK() OVER (PARTITION BY exam_id ORDER BY score desc) top_rnk , DENSE_RANK() OVER (PARTITION BY exam_id ORDER BY score) worse_rnk FROM Exam ) SELECT distinct e.student_id , student_name FROM Exam e JOIN Student s ON e.student_id = s.student_id WHERE e.student_id NOT IN ( SELECT sub.student_id FROM sub WHERE top_rnk = 1 OR worse_rnk = 1 ) ORDER BY student_id
Accepted (55.27%)
'SQL 문제풀이' 카테고리의 다른 글
leetcode - 2159. Order Two Columns Independently (0) 2022.09.15 leetcode - 1479. Sales by Day of the Week (0) 2022.09.14 leetcode - 2142. The Number of Passengers in Each Bus I (0) 2022.09.13 leetcode -2112. The Airport With the Most Traffic (0) 2022.09.13 leetcode - 2084. Drop Type 1 Orders for Customers With Type 0 Orders (0) 2022.09.13