简体   繁体   中英

Oracle 12c - Insert with multiple case conditions

I have 3 tables.

employee (emp_id, emp_active, emp_type, emp_status)
employee_salary (emp_id, emp_code, emp_salary)
employee_history (emp_id, emp_ind)

I need to insert into employee_history all employee.emp_id 's that meet all the following criteria:

employee.emp_active = 'Y'

employee.emp_id does not exist in employee_history

There are over 2 million records.

The value of emp_ind will be set using the following rules:

For emp_type A and B:

  • If the emp_status is A or B the emp_ind will be Y.
  • If the emp_status is C and either employee_salary.emp_code C or D have a emp_salary value greater than 0 then emp_ind will be Y.
  • If the emp_status is D or E the emp_ind will be N.
  • If the emp_status is F and employee_salary.emp_code C and D BOTH have a emp_salary value of 0 then emp_ind will be N.

For emp_type C, the emp_ind will be N

I can come up with a script to do most of this but i'm lost on how to code the case statements because of checking the values on multiple records in the employee_salary table. Hopefully someone can provide me a script for this.

I think this is what you need:

insert into employee_history (emp_id, emp_ind)
select
  e.emp_id,
  case when e.emp_status in ('A', 'B') then 'Y'
       when e.emp_status = 'C' and exists (
         select 1 from employee_salary s 
         where s.emp_id = e.emp_id
           and (s.emp_code = 'C' or s.emp_code = 'D' and s.emp_salary > 0)
       ) then 'Y'
       when e.emp_status in ('D', 'E') then 'N'
       when e.emp_status = 'F' and exists (
         select 1 from employee_salary s 
         where s.emp_id = e.emp_id and s.emp_code = 'C' s.emp_salary > 0
       ) and exists (
         select 1 from employee_salary s 
         where s.emp_id = e.emp_id and s.emp_code = 'D' s.emp_salary > 0
       ) then 'N'
  end
from employee e
where e.emp_active = 'Y'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM