I guess it is a homework (funny requirements for simple situations). Anyway, see if something like this helps.
SQL> set serveroutput on
SQL>
SQL> declare
2 l_avg number;
3 l_sum number := 0;
4 l_cnt number := 0;
5 begin
6 for cur_r in (select avg from test where age <= 20) loop
7 l_cnt := l_cnt + 1;
8 l_sum := l_sum + cur_r.avg;
9 end loop;
10
11 if l_cnt > 0 then
12 l_avg := l_sum / l_cnt;
13 end if;
14
15 dbms_output.put_line('Average is ' || nvl(to_char(l_avg), 'unknown'));
16 end;
17 /
Average is 68
PL/SQL procedure successfully completed.
SQL>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…