I've got a program that assigns employees with a "preferred vehicle" and at the end I make sure that no employees have the same vehicle.
The first loop gets a list of all preferred vehicles that occur more than once, and the nested loop goes through every employee that has that vehicle. In the end, only one employee will have it set as his/her preferred vehicle
--Loop through to see if a pref_veh occurs more than once
FOR every_duplicate_veh IN
(SELECT PREFERRED_VEH FROM FLEET_USER GROUP BY PREFERRED_VEH HAVING COUNT (PREFERRED_VEH) > 1)
LOOP
max_count:=0;
--Loop through all the employees with the duplicate vehicle
FOR every_employee IN (SELECT EMPLOYEE_ID FROM FLEET_USER WHERE PREFERRED_VEH=every_duplicate_veh.PREFERRED_VEH)
LOOP
--Find which employee is assigned the vehicle the most
SELECT COUNT(ASSIGN_VEH_ID) INTO assigned_veh_count FROM FLEET_TRANSACTION
WHERE ASSIGN_VEH_ID=every_duplicate_veh.PREFERRED_VEH AND DRIVER_EMP_ID=every_employee.EMPLOYEE_ID
AND SYSDATE - 30 <= RESERV_START_DT;
IF assigned_veh_count>max_count THEN
max_count:=assigned_veh_count;
preferred_employee_id:=every_employee.EMPLOYEE_ID;
END IF;
--Reset the employee's preferred vehicle to NULL
UPDATE FLEET_USER SET PREFERRED_VEH = NULL WHERE EMPLOYEE_ID = every_employee.EMPLOYEE_ID;
INSERT INTO FLEET_PREF_VEH_LOG VALUES (SYSDATE, every_employee.EMPLOYEE_ID, NULL);
END LOOP;
--One employee will get the preferred vehicle
UPDATE FLEET_USER SET PREFERRED_VEH = every_duplicate_veh.PREFERRED_VEH WHERE EMPLOYEE_ID = preferred_employee_id;
INSERT INTO FLEET_PREF_VEH_LOG VALUES (SYSDATE, preferred_employee_id, every_duplicate_veh.PREFERRED_VEH);
COMMIT;
END LOOP;
FLEET_USER is a table with thousands of rows...My goal is to eliminate the nested loop... can I do that? I'm still pretty new to sql so I would really appreciate any advice/point out anything I've missed