0

I am trying to figure out the round robin assignment of tasks to users.

I have a table of tasks and users and I want to assign new tasks to the users in the group but no user can have more than 2 tasks.

I want to assign the first task to the user who has the oldest date time stamp.

Current setup:

#newtasks
taskname:
task6
task7

assignedtasks:

userid task   last_update_date
11     task1  2018-05-29 15:30:17.410
22     task2  2018-05-30 15:30:17.410
22     task3  2018-05-31 15:30:17.410
33     task4  2018-06-01 15:30:17.410

What I want to see, userid 22 should not get a task as they have 2 tasks:

#assignedtasks:

userid task   last_update_date
11     task1  2018-05-29 15:30:17.410
11     task6  2018-06-01 16:30:17.410
22     task2  2018-05-30 15:30:17.410
22     task3  2018-05-31 15:30:17.410
33     task4  2018-06-01 15:30:17.410
33     task7  2018-06-01 16:30:17.410

Code to create tables:

IF Object_id ('TEMPDB..#newtasks') IS NOT NULL
DROP TABLE #newtasks

CREATE TABLE #newtasks
(
taskname VARCHAR(8)
)

INSERT INTO #newtasks
VALUES ('task6')
INSERT INTO #newtasks
VALUES ('task7')

SELECT * from #newtasks

IF Object_id ('TEMPDB..#assignedtasks') IS NOT NULL
DROP TABLE #assignedtasks

CREATE TABLE #assignedtasks
(
userid  INT,
task    VARCHAR(8),
last_update_date DATETIME
)

INSERT INTO #assignedtasks
VALUES ('11','task1',getdate()-4)
INSERT INTO #assignedtasks
VALUES ('22','task2',getdate()-3)
INSERT INTO #assignedtasks
VALUES ('22','task3',getdate()-2)
INSERT INTO #assignedtasks
VALUES ('33','task4',getdate()-1)

SELECT * FROM #assignedtasks
thirty
  • 177
  • 1
  • 2
  • 8

1 Answers1

0

Maybe you want to join on the row numbers order by the oldest last_update_date for the users and taskname for the tasks (as no other column is there to order by). To exclude users who already have two tasks use HAVING count(*) = 1.

INSERT INTO assignedtasks
            (userid,
             task,
             last_update_date)
            SELECT at.userid,
                   nt.taskname,
                   getdate()
                   FROM (SELECT at.userid,
                                ROW_NUMBER() OVER (ORDER BY max(at.last_update_date)) #
                                FROM assignedtasks at
                                GROUP BY at.userid
                                HAVING count(*) = 1) at
                        INNER JOIN (SELECT nt.taskname,
                                           ROW_NUMBER() OVER (ORDER BY nt.taskname) #
                                           FROM newtasks nt) nt
                                   ON nt.# = at.#;

SQL Fiddle

Still thinking a users table is missing though. What if a user has finished all their tasks?

sticky bit
  • 36,626
  • 12
  • 31
  • 42