/*
用PL/SQL语言编写一程序,实现按部门分段(6000以上、(6000,3000)、3000元以下)统计各工资段的职工人数、以及各部门的工资总额(工资总额不包括奖金)
*/
create table msg
(deptno number,
count1 number,
count2 number,
count3 number,
saltotal number);
SQL语句:
- 有哪些部门
select deptno from dept; à光标à循环à退出条件:notfound
2、部门中员工的薪水
select sal from emp where deptno=?; à带一个参数的光标à循环à退出条件notfound
变量:1、初始值2、如何得到
每个段的员工数:
count1 number,
count2 number,
count3 number,
每个部门的工资总额
saltotal number;
1、select sum(sal) into saltotal from emp where deptno=???
2、累加(这个方法比较好,但用第一个方法示例)
set serveroutput on
declare
--部门的光标
cursor cdept is select deptno from dept;
pdeptno dept.depeno%type;
--部门中员工的薪水
cursor cemp(dno number) is select sal from emp where deptno=dno;
psal emp.sal%type;
--每个段的员工人数
count1 number,
count2 number,
count3 number,
--每个部门的工资总额
saltotal number;
begin
--打开部门的光标
open cdept;
loop
--取出一个部门
fetch cdept into pdeptno;
exit when cdept%notfound;
--初始化工作
count1:=0;count2:=0;count3:=0;
--得到部门的工资总额
select sum(sal) into saltotal from emp where deptno=pdeptno;
--取出部门中员工的薪水
open cemp(pdepto);
loop
--取一个员工的薪水
fetch cemp into psal;
exit when cemp%notfound;
--判断薪水的范围
if psal<3000 then count1:=count1+1;
elsif psal>=3000 and psal<6000 then count2:=count2+1;
else count3:=count3+1;
end if;
end loop;
--关闭员工的光标
close cemp;
--保存当前部门的结果,nvl(saltotal,0)当saltotal值为空的时候,置为0,否则返回本身
insert into msg values(pdeptno,count1,count2,count3,nvl(saltotal,0));
end loop;
--关闭部门的光标
close cdept;
commit;
dbms_output.put_line(‘统计完成’);
end;
/