我想显示平均分数,但即使代码执行也没有显示,这是我的代码:
set serveroutput on size 10000;
declare
s_student_id grade.student_id%type;
g_score grade.score%type;
begin
for c in (select distinct grade.student_id, avg(grade.score) into s_student_id, g_score from grade inner join class on grade.class_id = class.class_id group by grade.student_id having count(class.course_id) > 4)
loop
dbms_output.put_line('Student' || c.student_id || ' :' || g_score);
end loop;
exception
when no_data_found then dbms_output.put_line('There are no students who selected more than 4 courses');
end;
/
输出:
anonymous block completed
Student1 :
答案 0 :(得分:2)
我认为这就是你所追求的:
set serveroutput on size 10000;
declare
v_counter integer := 0;
begin
for rec in (select grade.student_id,
avg(grade.score) g_score
from grade
inner join class on grade.class_id = class.class_id
group by grade.student_id
having count(class.course_id) > 4)
loop
v_counter := v_counter + 1;
dbms_output.put_line('Student: ' || rec.student_id || ', avg score: ' || rec.g_score);
end loop;
if v_counter = 0 then
raise no_data_found;
end if;
exception
when no_data_found then
dbms_output.put_line('There are no students who selected more than 4 courses');
end;
/
有几点需要注意:
into
子句 - 这仅适用于使用显式select语句的情况。您也不需要声明自己的变量来保存游标返回的数据 - cursor-for-loop声明记录变量以便为您返回行 - 在您的示例中,这将是c
,为了清楚起见,我已将其重命名为rec
。rec.student_id
,rec.g_score
。因此,如果你做的是直接选择以外的任何事情(例如我给了avg(grade.score)
一个别名,那么给你的列别名是很重要的,但我不需要为grade.student_id
而烦恼) RAISE
,或者,如果您需要传递用户定义的错误消息,请RAISE_APPLICATION_ERROR
。