Skip to content
Advertisement

SQL – Assign jobs to workers – Alternative to a loop?

In SQL Server 2019, I have a table of unassigned tasks, and another table of workers who are available to work on those tasks. My requirement is to assign the workers evenly over the available tasks by updating the WorkerID column in the Tasks table with the ID of the worker who will do the task.

  • Both the number of workers and the number of tasks can differ each time the SQL is run.
  • Either table may have more records than the other.
  • Task assignment just starts with the first worker in the Workers table and ends when the tasks are all assigned. (There is no randomizing of the workers for purposes of fairness from run to run.)
  • Either table can have zero records.

Given tables with the following structures, I would like to know how to do these assignments without using a loop. I suspect this can be done through the use of row numbers, rank, or some other such SQL Server magic, but I haven’t been able to figure it out. Thanks!

Tasks table:

Workers table:

Expected results for the Tasks table:

Advertisement

Answer

You can assign a number using window functions and then join. A “round-robin” method is:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement