Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

DECLARE CURSOR c1 IS SELECT sname, grade FROM Student s JOIN Taken t ON s.sid=t.

ID: 3761556 • Letter: D

Question

DECLARE
CURSOR c1 IS
SELECT sname, grade FROM Student s JOIN Taken t ON s.sid=t.sid
WHERE seqid='00001'
ORDER BY grade DESC;
-- my_sname VARCHAR2(40);
my_sname Student.sname%TYPE;
-- my_grade NUMBER(2,1);
my_grade Taken.grade%TYPE;
BEGIN
OPEN c1;
FOR i IN 1..3 LOOP
FETCH c1 INTO my_sname, my_grade;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total */
/* number of enrolled students in the class */
/* display the result */
dbms_output.put_line('Name: ' || my_sname || ' ' || 'Grade: ' || my_grade);
END LOOP;
CLOSE c1;
END;
/

Modify the above PL/SQL code to output the average of the top three grades.  

Explanation / Answer

The given PL/SQL code to implement a cursor and display the first 3 highest student’s grdes in the course with seqid ‘00001’ is given as follows:

DECLARE

CURSOR c1 IS

SELECT sname, grade FROM Student s JOIN Taken t ON s.sid=t.sid

WHERE seqid='00001'

ORDER BY grade DESC;

-- my_sname VARCHAR2(40);

my_sname Student.sname%TYPE;

-- my_grade NUMBER(2,1);

my_grade Taken.grade%TYPE;

BEGIN

OPEN c1;

FOR i IN 1..3 LOOP

FETCH c1 INTO my_sname, my_grade;

EXIT WHEN c1%NOTFOUND; /* in case the number requested */

/* is more than the total */

/* number of enrolled students in the class */

/* display the result */

dbms_output.put_line('Name: ' || my_sname || ' ' || 'Grade: ' || my_grade);

END LOOP;

CLOSE c1;

END;

/

The above code needs to be modified in such a way that it will implement a cursor to display the average of the top three grades as follows:

The student name and hi/her grade is selected for the student with the seqid (‘00001’) in the given code. The code given will fethch the top 3 grades. Calculate the sum of top three grades and after the end of the loop divide the sum by 3 to get the average of top 3 grades.

The modified parts of the code are highlighted in bold. The required modified PL/SQL code to display the average of top 3 grades is given as follows:

DECLARE

CURSOR c1 IS

SELECT sname, grade FROM Student s JOIN Taken t ON s.sid=t.sid

WHERE seqid='00001'

ORDER BY grade DESC;

-- my_sname VARCHAR2(40);

my_sname Student.sname%TYPE;

-- my_grade NUMBER(2,1);

my_grade Taken.grade%TYPE;

BEGIN

OPEN c1;

SUM:=0

AVG:=0

FOR i IN 1..3 LOOP

FETCH c1 INTO my_sname, my_grade;

EXIT WHEN c1%NOTFOUND; /* in case the number requested */

/* is more than the total */

/* number of enrolled students in the class */

SUM:=(SUM+my_grade);

/* display the result */

END LOOP;

CLOSE c1;

AVG:=(SUM/3);

dbms_output.put_line('Average of the Top 3 grade is '|| AVG);

END;