Oracle SQL中get_job_count函数如何去重统计员工不同岗位数量
Oracle HR样例库get_job_count函数修改方案
核心修改思路
你原来的函数是分别统计employees表的当前岗位记录、job_history表的历史任职记录的行数直接相加,没有对重复的job_id做去重,所以出现岗位来回变更时计数错误的问题。要实现统计不同岗位数量,只需要将两个表中该员工的所有job_id合并后去重,再统计总数即可。
修改后的完整函数代码
create or replace function get_job_count (E_id in employees.employee_id%type) return number is job_nb_total number; begin -- 合并两个表的job_id去重后计数 select count(distinct job_id) into job_nb_total from ( select job_id from employees where employee_id = E_id union all select job_id from job_history where employee_id = E_id ); if job_nb_total = 0 then raise_application_error(-20111,'Not Valid ID'); END IF; return job_nb_total; end; /
关键改动点说明
- 去掉了原来分开声明的
job_nb_employee、job_nb_history两个变量,无需分别统计两个表的行数 - 用子查询合并
employees和job_history中该员工的所有job_id,外层查询用count(distinct job_id)直接统计去重后的岗位总数 - 原有非法ID校验的逻辑完全保留,不影响原有异常处理逻辑
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

