是否有 SQL 更新查询来更新同一用户 ID 内的多条记录的相同值?

Is there a SQL update query to update the same value for multiple records within the same user id?

我有一列仅用于计算。它显示代表休假时间的 0 或正数。在我们的时间 table 中输入为负数,我将其转换为正数进行计算。对于员工的每个条目,我都需要该正值才能进入 NonWorkHrs 列。一个用户 ID 内的所有记录都必须是相同的值。

我试过在子查询中使用 case 语句和 select max

update DME
set NonWorkHrs = 
(
 select max(VacationHours)
 from DME b
 where useruid = b.useruid
 and useruid in (1,2,3)
 and NonWorkHrsHolder > 0
)
where useruid in (1,2,3)

我也试过case语句

update DME
set NonWorkHrs =
(case 
  when (VacationHours > 0)
  then (VacationHours)
 --no else statement is need. All rows should have the same value
 end
 ) 
where useruid in (1,2,3)

我将负的 TimeEntered 值转换为 VacationHours 列中的正值。 NonWorkHrs 列用于计算以确定实际工作时间。

预期结果是

Useruid UserFullName    NonWorkHrs  VacationHours   TimeEntered
1       Jane Doe         8             8             -8
1       Jane Doe         8             0              10
1       Jane Doe         8             0              12
2       John Doe         18            18            -18
2       John Doe         18            0              23
3       Bob Builder      16            16            -16
3       Bob Builder      16            0              40

实际结果是

Useruid UserFullName    NonWorkHrs  VacationHours   TimeEntered
1       Jane Doe          18           8             -8
1       Jane Doe          18           0              10
1       Jane Doe          18           0              12
2       John Doe          18           18            -18
2       John Doe          18           0              23
3       Bob Builder       18           16            -16
3       Bob Builder       18           0              40

这个查询应该可以,试一试。

DECLARE @DME TABLE
(
Useruid int,
UserFullName varchar(200),
NonWorkHrs  int,
VacationHours   int,
TimeEntered int
)

INSERT INTO @DME
VALUES
(1,'Jane Doe',18,8,-8),
(1,'Jane Doe',18,0,10),
(1,'Jane Doe',18,0,12),
(2,'John Doe',18,18,-18),
(2,'John Doe',18,0,23),
(3,'Bob Builder',18,16,-16),
(3,'Bob Builder',18,0,40)

SELECT d.* FROM @DME d

    UPDATE @DME
        SET NonWorkHrs = T2.VacationHours
    FROM @DME T1
    INNER JOIN (SELECT Max(VacationHours) AS VacationHours, Useruid FROM @DME GROUP BY Useruid) AS T2 
    ON T2.Useruid = T1.Useruid


SELECT d.* FROM @DME d

使用CTE:

  ;WITH vacationsPerUser as (
      SELECT userId, max(VacationHours) as maxVacationHours
      FROM DME 
      WHERE useruid in (1,2,3)
        and NonWorkHrsHolder > 0
      GROUP BY userId
     )
  Update b
    SET b.NonWorkHrs = ISNULL(vacationsPerUser.maxVacationHours, 0)
    FROM DME b 
    LEFT JOIN vacationsPerUser
         ON vacationsPerUser.UserId = b.UserId
    WHERE b.useruid in (1,2,3);

或者这个(给出与您预期的结果相同的结果)

UPDATE a
    SET NonWorkHrs = ABS(sub.minNegativeTime)
FROM DME a
INNER JOIN (
    SELECT useruid, MIN(TimeEntered) minNegativeTime
    FROM DME b
    WHERE b.TimeEntered < 0
    GROUP BY Useruid
) sub ON sub.Useruid = a.Useruid