结果汇总表:
思路:两次遍历(loop),第一次遍历部门,第二次在每个部门中遍历员工薪水;
首先建立表msg,用来保存题目要求的数据
1 create table msg 2 ( 3 deptno number, 4 count1 number, 5 count2 number, 6 count3 number, 7 saltotal number 8 );
然后逐个部门统计薪水:
1 set serveroutput on 2 3 declare 4 --定义部门的光标(部门号) 5 cursor cdept is select deptno from dept; 6 pdeptno dept.deptno%type; 7 8 --各部门中每个员工的薪水(员工薪水) 9 cursor cemp(dno number) is select sal from emp where deptno=dno; 10 psal emp.sal%type; 11 12 --每工资段的员工人数 13 count1 number; 14 count2 number; 15 count3 number; 16 17 --每个部门的工资总额 18 saltotal number; 19 20 begin 21 open cdept;--打开部门的光标 22 loop 23 24 fetch cdept into pdeptno; --取出一个部门 25 exit when cdept%notfound; 26 --初始化工作 27 count1:=0; 28 count2:=0; 29 count3:=0; 30 --得到部门的工资总额 31 select sum(sal)into saltotal from emp where deptno=pdeptno; 32 33 open cemp(pdeptno); --取部门中员工的薪水 34 loop 35 --取一个员工的薪水 36 fetch cemp into psal; 37 exit when cemp%notfound; 38 --判断薪水的范围 39 if psal<3000 then count1:=count1+1; 40 elsif psal>=3000 and psal<6000 then count2:=count2+1; 41 else count3:=count3+1; 42 end if; 43 end loop; 44 close cemp; 45 --保存当前部门的结果 46 insert into msg values(pdeptno,count1,count2,count3,nvl(saltotal,0));--nvl:当saltotal为null时返回0,若不为null时返回原数字 47 48 end loop; 49 close cdept;--关闭部门的光标 50 51 --提交 52 commit; 53 dbms_output.put_line('统计完成'); 54 end; 55 / 56
结果:
查询msh表可得: