我已经把这个查询写成显示加班,如果有人工作时间超过下午18:00时钟时间,无论他/她来的时间或他/她工作的工作时间,这都超出了主题。它只显示OVERTIME,如果有人在18:00 pm以上工作,那就是它,例如InTime = 15:16 pm,TimeOut = 18:31然后Overtime = 00:31。所以我写了下面给出的这个问题,但现在问题是下午17:00离职的人数很少,他们的超时时间应该在下午17:00之后计算(他在上午17:00以后工作了多少分钟+小时),所以那些具体的员工超时应该在17:00之后计算
那些员工是:
EmplID 5, 43, 11
所以只有这些加班才能在17:00之后计算出来。
查询:
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS InTime
, max(t2.RecTime) AS [TimeOut]
, cast(min(t1.RecTime) as datetime) AS InTimeSub
, cast(max(t2.RecTime) as datetime) AS TimeOutSub
, t1.RecDate AS [DateVisited]
FROM AtdRecord t1
INNER JOIN
AtdRecord t2
ON t1.EmplID = t2.EmplID
AND t1.RecDate = t2.RecDate
AND t1.RecTime < t2.RecTime
inner join
HrEmployee t3
ON t3.EmplID = t1.EmplID
group by
t1.EmplID
, t3.EmplName
, t1.RecDate
)
SELECT EmplID
,EmplName
,InTime
,[TimeOut]
,[DateVisited]
,convert(char(5),cast([TimeOutSub] - InTimeSub as time), 108) totaltime
,CONVERT(char(5),CASE WHEN CAST([TimeOutSub] AS DATETIME) >= '18:00' Then
LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST('18:00' AS DATETIME),
CAST([TimeOutSub] AS DATETIME)),0), 108),5) ELSE '00:00' END, 108) AS OVERTIME
FROM times
输出:
答案 0 :(得分:1)
尝试更换:
CASE WHEN CAST([TimeOutSub] AS DATETIME) >= '18:00' Then
LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST('18:00' AS DATETIME),
CAST([TimeOutSub] AS DATETIME)),0), 108),5) ELSE '00:00' END, 108) AS OVERTIME
用
CASE WHEN CAST([TimeOutSub] AS DATETIME) >= '18:00' And EmplId Not In (5,43,11)
Then LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST('18:00' AS DATETIME), CAST([TimeOutSub] AS DATETIME)),0), 108),5)
WHEN CAST([TimeOutSub] AS DATETIME) >= '17:00' And EmplId In (5,43,11)
Then LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST('17:00' AS DATETIME), CAST([TimeOutSub] AS DATETIME)),0), 108),5)
ELSE '00:00' END, 108) AS OVERTIME
基本上,我只在WHEN
部分添加了多个条件。 When time > 18:00
和emplid not IN (5,43,11)
以及time > 17:00 and emplid in (5,43,11).
将其理解为伪代码可能更容易:
CASE WHEN TIME >= '18:00' And EmplId Not In (5,43,11)
Then -- Calculate overtime at 18:00
WHEN TIME >= '17:00' And EmplId In (5,43,11)
Then -- Calculate overtime at 17:00
ELSE '00:00'
END OVERTIME