Oracle SQL Cursor增加工资直到达到最大金额

时间:2017-10-13 20:45:11

标签: sql oracle cursor procedure

对于这个问题,我需要从最低工资(asc订单)开始增加20%的员工薪水,直到$ 100,000用尽。我很难找到如何保存更新金额的解决方案,直到使用100,000美元。这就是我到目前为止所拥有的。谢谢

declare
 cursor mancur is
   select salary from employees order by salary asc;
 tempcur     mancur%ROWTYPE;
 profits     number := 100000;
 tempsalary  employees.salary%type;
 tempinc     number(8,2);
begin
 open mancur;
 loop
   fetch mancur into tempcur;
   tempinc := tempcur.salary * 1.20;
   tempsalary := profits - tempcur.salary;
   dbms_output.put_line(tempcur.salary || ' increased by 20% ' || tempinc || ', Bonus amount left ' || tempsalary);
   exit when mancur%notfound; --when 100,000 has been used
   --update employees set salary = salary * 1.20 where employee_id = tempcur.employee_id;
 end loop;
 close mancur;
end;
/

3 个答案:

答案 0 :(得分:1)

begin
 open mancur;
  loop
   fetch mancur into tempcur;
   tempinc := tempcur.salary * 1.20;
   profits := profits - (tempinc-tempcur.salary);  -- You have to keep subtracting the increment amount to find if bonus is exhausted or not
      if profits <=0 Then  --When all your funds are exhausted
         Exit
      End if
              dbms_output.put_line(tempcur.salary || ' increased by 20% ' || tempinc || ', Bonus amount left ' || profits);
      exit when mancur%notfound; --when 100,000 has been used
   --update employees set salary = salary * 1.20 where employee_id = 
      tempcur.employee_id;
   end loop;
 close mancur;
end;
/

答案 1 :(得分:0)

declare
 profits     number := 100000;
 tempinc     number(8,2);
begin
for hike_loop in (select employee_id,salary from employees order by salary asc) loop
if profits <= 0 then
break;
end if;
tempinc := hike_loop.salary * 0.20;
if (tempinc <= profits) then
update employees set salary = salary * 1.20 where employee_id = hike_loop.employee_id;
profits := profits - tempinc;
else
break;
end if;
end loop;
end;
/

答案 2 :(得分:0)

只是为了好玩:这是如何在纯SQL中完成的。除非是PL / SQL类中的家庭作业,否则不需要执行此任务的功能或过程。即便如此,应该从PL / SQL代码运行相同的MERGE语句,以便处理在设置级别完成,而不是逐行完成。

这也解决了剩余的小额&#34;与目前发布的解决方案不同。如果没有足够的话来增加&#34;最后的&#34;工资增加了20%,然后增加了多少,最高可达10万美元。如果两个或两个以上具有相同工资的员工是第一个被排除在外的员工,那么剩下的&#34;剩余金额&#34;这些员工之间平均分配。

merge into employees e
  using ( select employee_id,
                 sum  (salary) over (order by salary)     as sum_salary,
                 count(salary) over (partition by salary) as cnt
          from   employees
        ) x
    on ( e.employee_id = x.employee_id )
when matched then update
  set salary = 1.2 * salary + case when sum_salary <= 100000 / 0.2 then 0
                                   else (100000 - 0.2 * sum_salary) / cnt end  
    where sum_salary - cnt * salary <= 100000 / 0.2
;