Here is a solution that gives the expected results from your sample data. However, I am bending the rules! What I do is that I order the users on the current total number of tasks, and then I assign then tasks from the Tasks table in a round-robin fashion.
Depending on the business rules for your actual problem, this may be good enough - or it may be entirely inappropriate. But at least it is a relatively simple solution, and it is a single statement.
You never said whether you are using a serverless or dedicated pool, but this runs in the master database of my Synapse workspace, which I believe is the serverless pool.
CREATE TABLE #Users (
UserID VARCHAR(2),
TotalTasks INT
);
-- Insert data into Users table
INSERT INTO #Users (UserID, TotalTasks) VALUES
('A3', 12),
('A4', 14),
('A5', 11);
-- Create the Tasks table
CREATE TABLE #Tasks (
TaskID INT,
NewTask INT
);
-- Insert data into Tasks table
INSERT INTO #Tasks (TaskID, NewTask) VALUES
(1, 4),
(2, 5),
(3, 3),
(4, 2);
WITH UserNumbering AS (
SELECT UserID, TotalTasks,
QueueOrder = row_number() OVER(ORDER BY TotalTasks),
NoOfUsers = COUNT(*) OVER()
FROM #Users
), TaskNumbering AS (
SELECT TaskID, NewTask,
TaskNo = row_number() OVER (ORDER BY TaskID) - 1
FROM #Tasks
)
SELECT T.TaskID, T.NewTask, U.UserID,
UpdatedTasks = U.TotalTasks + SUM(T.NewTask) OVER(PARTITION BY U.UserID
ORDER BY T.TaskNo
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM TaskNumbering T
JOIN UserNumbering U ON U.QueueOrder = T.TaskNo % U.NoOfUsers + 1
ORDER BY T.TaskID
go
DROP TABLE #Tasks
DROP TABLE #Users