As per my comment, the first time you run this the task should be assigned to 004 - PAT as they currently do not have any tasks at all assigned to them.
This code will do what you want:
UPDATE [tasks] SET AssignedTo =
(select TOP 1 idno
from [Master] M left outer join [tasks] T on M.idno=T.AssignedTo
group by idno
order by COUNT(t.taskID) )
WHERE AssignedTo IS NULL
Things to note:
- the use of
TOP 1
to only get a single idno
- The
ORDER BY
so the one with the least assignments filters to the top
- I used a table like this
creeate table [tasks]
(
taskID int identity(1,1),
Task nvarchar(150),
AssignedTo int
)
- Note the
WHERE
clause so I only update the unassigned records
The first time you run this code you may get a warning about NULL values
Quote:
Warning: Null value is eliminated by an aggregate or other SET operation.
This can be ignored and will not appear once all entries on the [Master] table have at least one Task assigned to them
To be clear I used the following test data
insert into [Master] values
('JAMES'),
('PAUL'),
('MAY'),
('PAT')
insert into [tasks] values
('John Smith',1),
('Sarah Adams',1),
('Michael Jones',1),
('Godfred Arthur',2),
('David Lawson',2),
('Jennifer Bruce',3),
('new item',null)
So the starting point is:
JAMES has 3 tasks assigned
PAUL has 2 tasks assigned
MAY has 1 task assigned
PAT has no tasks assigned to them.
There are 7 tasks on the table, all but one of them are assigned to someone.
Extrapolating the code above this section
SELECT idno, name, count(t.taskID)
from [Master] M left outer join [tasks] T on M.idno=T.AssignedTo
group by idno, name
order by COUNT(t.taskID)
gives the results
4 PAT 0
3 MAY 1
2 PAUL 2
1 JAMES 3
So the bit I actually used
select TOP 1 idno
from [Master] M left outer join [tasks] T on M.idno=T.AssignedTo
group by idno
order by COUNT(t.taskID)
will return the value
4
.
That value will be assigned to
all rows on the table where the
AssignedTo
column is null.
Importantly, as in your case in the comments, if no rows have a null value in the AssignedTo column then
nothing will be updated and the counts for each row on the Master table will remain unchanged
If I add a new row
insert into tasks values ('item 2',null)
and run the code again, the second time through both MAY and PAT only have 1 task each. It's likely that MAY be assigned the new task simply because that Id is lower than PAT, but this is not guaranteed.