为什么我的查询行为异常?我已经做了很多努力使它工作,我做了某种方式使它通过stackoverflow帖子等工作但仍然有一些问题
我正在尝试计算一个人的总工作时间,例如通过查找Intime和Outtime之间的差异,它可以工作,但是对于某些记录,它显示错误的工作时间
e.g。
InTime TimeOut total time
12:00 18:11 5:11 // wrong, it should be 6:11
13:01 18:20 4:19 // Wrong,
09:33 17:15 7:42 // It fine and correct
与许多记录一样,它可以正常工作,但有些记录却没有,总是显示-1小时的实际值。
WITH times
AS (
SELECT t1.EmplID
,t3.EmplName
,min(t1.RecTime) AS InTime
,max(t2.RecTime) AS [TimeOut]
,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]
,CASE
WHEN minpart = 0
THEN CAST(hourpart AS NVARCHAR(200)) + ':00'
ELSE CAST((hourpart - 1) AS NVARCHAR(200)) + ':' + CAST(minpart AS NVARCHAR(200))
END AS 'total time'
FROM (
SELECT EmplID
,EmplName
,InTime
,[TimeOut]
,[DateVisited]
,DATEDIFF(Hour, InTime, [TimeOut]) AS hourpart
,DATEDIFF(minute, InTime, [TimeOut]) % 60 AS minpart
FROM times
) source
这篇文章几乎让它起作用,但后来我发现了问题。 DateDiff to output hours and minutes
输出:
EmplID EmpName InTime TimeOut DateVisited Total time
00000024 Tariq 09:59 18:56 2013-09-21 8:57
00000024 Tariq 10:57 19:00 2013-09-23 8:3
00000024 Tariq 11:40 18:58 2013-09-24 7:18
答案 0 :(得分:1)
SELECT EmplID
,EmplName
,InTime
,[TimeOut]
,[DateVisited]
,CASE
WHEN minpart = 0
THEN CAST(hourpart AS NVARCHAR(200)) + ':00'
WHEN minpart <10
THEN CAST(hourpart AS NVARCHAR(200)) + ':0'+ CAST(minpart AS NVARCHAR(200))
ELSE CAST(hourpart AS NVARCHAR(200)) + ':' + CAST(minpart AS NVARCHAR(200))
END AS 'total time'
FROM (
SELECT EmplID
,EmplName
,InTime
,[TimeOut]
,[DateVisited]
,DATEDIFF(minute, InTime, [TimeOut])/60 AS hourpart
,DATEDIFF(minute, InTime, [TimeOut]) % 60 AS minpart
FROM times
) source
答案 1 :(得分:1)
只需将会议记录作为约会,然后重新开始
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS InTime
, max(t2.RecTime) AS [TimeOut]
, t1.RecDate AS [DateVisited]
, DATEDIFF(minute,min(t1.RecTime), max(t2.RecTime)) TotalMin
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]
, CAST((TotalMin / 60) as varchar(2)) + ':' + CAST((TotalMin % 60) as varchar(2)) as [total time]
from times
Order By EmplID, DateVisited