Oracle SQL change value of field to other value from list as long as new value different from current?

StackOverflow https://stackoverflow.com/questions/23345639

  •  11-07-2023
  •  | 
  •  

Question

I have a test table which contains 33 employee records in my Oracle 10g XE. Examples are as the following (I'm showing 5 only):

enter image description here

I'm not a SQL person so I only know those basic INSERT, UPDATE etc. What I want to achive is to change the department of each employee to another department from another employee as long as it's not the same as their current department. Basically what I'm thinking is:

  1. Get all of the department from each employee (DEPT A, DEPT B, DEPT B, DEPT C, DEPT A), maybe store it in a variable?
  2. For each of the employee, put a different department into its record from the list of department collected before. The new department must not be the same as what that record has before.
  3. The result of the above example would be like the following.

enter image description here

For the record, there are more than just DEPT A - C. My 33 employee records mostly have unique department. Only 2 - 3 department have more than 1 employee under it. Therefore, I can assure that there probably won't be any cases where an employee record cannot be assign under a different department from what it currently has.

Was it helpful?

Solution

This is a harder problem than you may realize. First, it is a permutation problem because you want the final counts for the departments to be the same. Second, there are times where it is not solvable (say, if more than half the employees are in the same department).

If you want to shuffle the departments for employees, here is a method:

with cte as (
      select e.*,
             row_number() over (order by emp_id) as orig_seqnum,
             row_number() over (order by dbms_random.value) as new_seqnum
      from employees e
     )
select e1.*, e2.dept as new_dept
from cte e1 join
     cte e2
     on e1.orig_seqnum = e2.new_seqnum;

This does not guarantee that the new department is different from the old one. There are actually ways to make that happen. However, given that most of your departments have only one employee, this might solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top