1

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

我尝试过使用 case 语句并在子查询中选择 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)

我还尝试了一个案例陈述

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)

我在 VacationHours 列中将负 TimeEntered 值转换为正值。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
4

3 回答 3

0

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

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
于 2019-04-18T13:45:02.450 回答
0

使用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);
于 2019-04-18T13:50:41.953 回答
0

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

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
于 2019-04-18T13:54:07.460 回答