oracle PL/SQL -用于检查薪金的If语句

icomxhvb  于 2023-02-15  发布在  Oracle
关注(0)|答案(2)|浏览(120)

我正在尝试开发一个程序,它从用户那里获取一个数字,按最高工资对雇员进行排序,并显示与输入数字相等的行数,以显示最高收入者。该程序还应该验证上一个雇员是否与下一个雇员获得了相同的工资。如果是这样,下一个雇员也应该显示出来。
我试图修改代码,但似乎没有任何更改有效。您对如何使代码按照提供的说明运行有什么建议吗?功能代码包括在下面。
谢谢你。
代码:

CREATE OR REPLACE PROCEDURE p5_q5 (num_employee NUMBER) AS
BEGIN
  FOR emp IN (SELECT ENAME, SAL
              FROM EMP
              ORDER BY SAL DESC
              FETCH FIRST num_employee ROWS ONLY) -- Will be returned X rows according to input of the user (num_employee)
  LOOP
    DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp.ENAME || ' - Salary: ' || emp.SAL);
  END LOOP;
END;
/

EXEC p5_q5(3);
  • 产出:

员工姓名:国王-薪金:5512.5员工姓名:琼斯-工资:3570员工姓名:斯科特-工资:3450

  • 理想输出:

员工姓名:国王-薪金:5512.5员工姓名:琼斯-工资:3570员工姓名:斯科特-工资:3450员工姓名:福特-薪酬:3450
我尝试了几种策略,但都没有成功地开发出一种方法来确定下一个员工是否与上一个员工挣到相同的薪水,并在他们挣到相同的薪水时显示该员工。

xqkwcwgp

xqkwcwgp1#

使用FETCH FIRST n ROWS WITH TIES

CREATE OR REPLACE PROCEDURE p5_q5 (num_employee NUMBER) AS
BEGIN
  FOR emp IN (SELECT ENAME, SAL
              FROM EMP
              ORDER BY SAL DESC
              FETCH FIRST num_employee ROWS WITH TIES)
  LOOP
    DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp.ENAME || ' - Salary: ' || emp.SAL);
  END LOOP;
END;
/

其中,对于示例数据:

CREATE TABLE emp (ename, sal) AS
  SELECT 'Alice', 100 FROM DUAL UNION ALL
  SELECT 'Betty', 100 FROM DUAL UNION ALL
  SELECT 'Carol',  90 FROM DUAL UNION ALL
  SELECT 'Debra',  90 FROM DUAL UNION ALL
  SELECT 'Emily',  90 FROM DUAL;

然后:

BEGIN
  DBMS_OUTPUT.ENABLE;
  p5_q5(1);
END;
/

以及

BEGIN
  DBMS_OUTPUT.ENABLE;
  p5_q5(2);
END;
/

两个输出:

Employee name: Alice - Salary: 100
Employee name: Betty - Salary: 100

以及:

BEGIN
  DBMS_OUTPUT.ENABLE;
  p5_q5(3);
END;
/

输出:

Employee name: Alice - Salary: 100
Employee name: Betty - Salary: 100
Employee name: Carol - Salary: 90
Employee name: Debra - Salary: 90
Employee name: Emily - Salary: 90

fiddle

8ehkhllq

8ehkhllq2#

CREATE OR REPLACE PROCEDURE p5_q5 (num_employee NUMBER) AS
curr_salary NUMBER;
BEGIN
curr_salary := 0;
FOR emp IN (SELECT ENAME, SAL
FROM EMP
ORDER BY SAL DESC)
LOOP
IF emp.SAL = curr_salary THEN
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp.ENAME || ' - Salary: ' || emp.SAL);
num_employee := num_employee - 1;
ELSE
curr_salary := emp.SAL;
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp.ENAME || ' - Salary: ' || emp.SAL);
num_employee := num_employee - 1;
END IF;
IF num_employee = 0 THEN
  EXIT;
END IF;
END LOOP;
END;
/

EXEC p5_q5(3);

相关问题