2017-10-13 52 views
1

對於這個問題,我需要將僱員數量增加20%,以最低工資(asc訂單)開始,直到耗盡100,000美元。我很難找到一個解決方案,如何保存更新的金額,直到使用$ 100,000。這是我迄今爲止所擁有的。謝謝Oracle SQL光標增加工資,直到達到最大數量

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; 
/
+0

這是生產問題還是作業問題?如果它是作業,是PL/SQL類嗎?使用單個SQL語句可以更高效地解決此需求。 – mathguy

+2

另外,你如何處理關係?假設你上了名單,現在下一個員工(他們的薪水還沒有增加)是三名同樣薪水的員工。他們目前的薪水是每人30,000美元,所以他們每人應該得到6,000美元,但只剩下12,000美元。誰得到了多少? – mathguy

回答

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; 
/
+0

謝謝! Idk我怎麼弄不懂。時間從屏幕休息一下哈 – namesjj

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; 
/
0

只是爲了好玩:這裏是應如何在普通的SQL來完成。除非它是PL/SQL類中的作業,否則不需要此任務的函數或過程。即使如此,應該從PL/SQL代碼運行相同的MERGE語句,以便處理在設置的級別完成,而不是逐行完成。

這也解決了迄今爲止發佈的解決方案中的「小剩餘量」問題。如果沒有足夠的「最後」工資增加20%,那麼增加的幅度可能高達10萬美元。如果兩名或兩名以上薪酬相同的員工是「第一個被排除在外」,那麼「剩餘數量」在這些員工之間平分。

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 
;