Write a query to find the name of the student(s) who has scored maximum mark in Software Engineering. Sort the result based on name

前端 未结 4 1253
生来不讨喜
生来不讨喜 2020-12-22 05:24

Write a query to find the name of the student(s) who has scored maximum mark in Software Engineering. Sort the result based on name.

This is what I tried.

         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-22 05:41

    Apart from the fact that you're using outdated implicit comma syntax for joins, you are also combining columns of the tables in the wrong way in the sub query.

    subject_name is a column of subject which has nothing to do with the student's relation to marks. So, mark may be joined separately with subject while determining the student_ids with highest mark. We can then obtain the name of the student using those student_ids

    So, In Oracle 12c and above, you could do

    SELECT s.student_name
       FROM student s
    WHERE s.student_id IN ( SELECT m.student_id
                            FROM mark m JOIN subject su 
                             ON su.subject_id = m.subject_id
                            WHERE lower(su.subject_name) = 'software engineering'
                               ORDER BY m.value DESC
                            FETCH FIRST 1 ROWS WITH TIES ) order by 1;  
    

    For previous versions, you may use dense_rank or rank

    SELECT s.student_name
       FROM student s
    WHERE s.student_id IN ( SELECT student_id
                            FROM ( SELECT m.*,DENSE_RANK() OVER(
                                        ORDER BY m.value DESC
                                   ) AS rnk
                                   FROM mark m  JOIN subject su 
                                    ON su.subject_id = m.subject_id
                            WHERE lower(su.subject_name) = 'software engineering'
                        ) WHERE rnk = 1
                   ) order by 1;     
    

提交回复
热议问题