简体   繁体   中英

Sub Query SQL Oracle

I need to create a sub query which shows student_id, student_first_name, module_name, and maths grade (subject 'Maths') for the students who have the highest grade for each module. The student table is linked to the grade table via student_id and the module_name, grade and subject is stored in the grade table. But what I have doesn't seem to be right

SELECT S.STUDENT_ID, S.LAST_NAME, G.SECTION_ID, G.MODULE_NAME, G.GRADE
FROM STUDENT S, GRADE G
WHERE S.STUDENT_ID = G.STUDENT_ID
AND G.GRADE IN (SELECT MAX(GRADE) FROM GRADE G WHERE G.Subject = 'Maths')

Try the following query

SELECT S.STUDENT_ID, S.LAST_NAME, G.SECTION_ID, G.MODULE_NAME, G.GRADE
FROM STUDENT S
JOIN GRADE G ON S.STUDENT_ID = G.STUDENT_ID
JOIN (
    SELECT G.MODULE_NAME, MAX(G.GRADE) max_grade
    FROM GRADE G 
    WHERE G.Subject = 'Maths'
    GROUP BY G.MODULE_NAME
) t ON G.MODULE_NAME = t.MODULE_NAME and
       G.GRADE = t.max_grade and
       G.Subject = 'Maths'

There is no need to use a subquery for this. One solution is analytic functions:

SELECT SG.STUDENT_ID, SG.LAST_NAME, SG.SECTION_ID, SG.MODULE_NAME, SG.GRADE
FROM (SELECT S.STUDENT_ID, S.LAST_NAME, G.SECTION_ID, G.MODULE_NAME, G.GRADE,
             MAX(G.GRADE) OVER (PARTITION BY MODULE_NAME) as MAX_GRADE
      FROM STUDENT S JOIN
           GRADE G
           ON S.STUDENT_ID = G.STUDENT_ID
      WHERE G.Subject = 'Maths'
     ) sg
WHERE GRADE = MAX_GRADE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM