我有2个表,任务和员工。这些都在关系数据库中。
我想要做的是使用4个staffID(1,2,3,4)更新Tasks表中的StaffID列,并在迭代中执行,最终结果将是:
那么StaffID' 1'将有任务1,5,9等,以及所有其他staffID做同样的事情。到目前为止,我的查询看起来像这样,但我确定我错过了很多东西:
update Tasks
set StaffID = 2
where
这就是我所拥有的,在此之后,我对我需要做什么感到难过。对此的任何帮助或指向如何执行此操作的文档链接都会很棒。
答案 0 :(得分:0)
create table task as
WITH tasks as
(select 1 taskid,1 staffid, 'Task 1' title,getdate()-1 createdDate union all
select 2 taskid,1 staffid, 'Task 2' title,getdate()-2 createdDate union all
select 3 taskid,1 staffid, 'Task 3' title,getdate()-3 createdDate union all
select 4 taskid,1 staffid, 'Task 4' title,getdate()-4 createdDate union all
select 5 taskid,1 staffid, 'Task 5' title,getdate()-5 createdDate union all
select 6 taskid,1 staffid, 'Task 6' title,getdate()-6 createdDate union all
select 7 taskid,1 staffid, 'Task 7' title,getdate()-7 createdDate union all
select 8 taskid,1 staffid, 'Task 8' title,getdate()-8 createdDate union all
select 9 taskid,1 staffid, 'Task 9' title,getdate()-9 createdDate
)
SELECT * FROM tasks
update task
set staffid = case when mod(taskid,4) =1 then 1
when mod(taskid,4) =2 then 2
WHEN mod(taskid,4) =3 then 3
WHEN mod(taskid,4) =0 then 4
end from task b
where taskid=b.taskid;
答案 1 :(得分:0)
如果您知道taskid没有间隙,那么对其进行算术将解决您的问题。否则,您可以使用row_number()
:
with toupdate as (
select t.*, row_number() over (order by t.taskid) as seqnum
from tasks t
)
update toupdate
set staffid = ((seqnum - 1) % 4) + 1;
答案 2 :(得分:0)
您可以使用此功能为员工分配任务,请阅读评论以适应您的需求(如果需要)。
DECLARE @AmountStaffToAssign INT = 4
;WITH SequentialStaffIDs AS
(
-- Get a sequential ID asigned to each of your StaffID (if not already sequential)
SELECT TOP (@AmountStaffToAssign)
S.StaffID,
SequentialID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM
Staff AS S
-- You can filter your staff to reassign here and also order them
),
SequentialTaskIDs AS
(
-- Get a sequential ID asigned to each of your TaskID (if not already sequential)
SELECT
S.TaskID,
SequentialID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM
Task AS S
-- You can filter you tasks to be assigned here
),
TaskReassignment AS
(
SELECT
T.TaskID,
T.SequentialID,
StaffSequentialID = ((T.SequentialID - 1) % @AmountStaffToAssign) + 1
FROM
SequentialTaskIDs AS T
)
UPDATE T SET
StaffID = S.StaffID
FROM
Task AS T
INNER JOIN TaskReassignment AS R ON T.TaskID = R.TaskID
INNER JOIN SequentialStaffIDs AS S ON R.StaffSequentialID = S.SequentialID
答案 3 :(得分:0)
以下是我的答案:https://sqleditor.net/q/rk6YcdEtM
UPDATE T SET StaffID = S.StaffID
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY TaskID) % (SELECT COUNT(*) FROM Staff) AS seq, StaffID FROM Tasks
) T
INNER JOIN (
SELECT ROW_NUMBER() OVER (ORDER BY StaffID) % (SELECT COUNT(*) FROM Staff) AS seq, StaffID FROM Staff
) S ON T.seq = S.seq;
GO
您可以在此处尝试更多详细信息:https://sqleditor.net/q/rk6YcdEtM