1我的目的是什么:
I try to get two person from each department with highest salary.
2我如何努力实现它:
DECLARE
TYPE empl_table IS TABLE OF employees.employee_id%type INDEX BY binary_integer;
empl empl_table;
CURSOR departmennts_id IS
SELECT department_id FROM departments;
BEGIN
FOR depart_row IN departmennts_id
loop
SELECT employee_id BULK COLLECT into empl
FROM
(
SELECT employee_id
FROM employees
where DEPARTMENT_ID= depart_row.department_id
ORDER BY salary DESC
)
WHERE ROWNUM<3;
END loop;
END;
3问题出在哪里:
where DEPARTMENT_ID= depart_row.department_id
当我将depart_row.department_id更改为固定身份证号码(例如80) 查询工作。如果我使用depart_row.department_id,则empl.count为0。
我在哪里弄错了?
答案 0 :(得分:0)
对于外部游标的每次迭代,您将行放入EMPL_TABLE。每次代码循环返回另一个department_id然后重新执行内部SELECT时, 将替换集合的内容 。因此,如果外部光标看到的LAST部门碰巧没有与之关联的员工,那么最终会得到一个空集合。
您最好的办法是取消DEPARTMENTS上的单独光标,只需使用一个可以完成所需操作的光标,如:
SELECT *
FROM (SELECT DEPARTMENT_ID,
SALARY,
ROW_NUMBER() OVER
(PARTITION BY DEPARTMENT_ID
ORDER BY SALARY DESC) AS EMP_RANK
FROM EMPLOYEES
ORDER BY DEPARTMENT_ID, EMP_RANK)
WHERE EMP_RANK < 3
分享并享受。