데이터 유형이 TIME
이고 시간이 저장되어 있고 -00:29
이 아니기 때문에 (즉,이 시간은 하루에 발생하지 않음)
당신이하려는 것은 시간을 표시하는 데 사용되는 일반적인 형식으로 표시 기간을 표시하는 것입니다. 이것은 시간을 표시하는 것과 동일하지 않습니다. 이것은 단순히 실행하여 공정하게 표시 할 수 있습니다 : 00:00
마이너스 00:31
전날의 23:29
때문에
Conversion failed when converting date and/or time from character string.
이유가 표시됩니다 이것이다 : 오류가 발생합니다
SELECT CAST('-00:27' AS TIME)
합니다.
저는 개인적으로 모든 계산을 분 단위로 수행합니다.
SELECT StartTime,
EndTime,
HoursWorked = DATEDIFF(MINUTE, StartTime, EndTime)/60.0,
MinutesOver = 480 - DATEDIFF(MINUTE, StartTime, EndTime)
FROM (VALUES
(CAST('06:50' AS TIME), CAST('15:20' AS TIME)),
(CAST('07:50' AS TIME), CAST('15:20' AS TIME))
) t (StartTime, EndTime);
주는 :
StartTime | EndTime | HoursWorked | MinutesOver
----------+----------+-------------+------------
06:50:00 | 15:20:00 | 8.5 | -30
07:50:00 | 15:20:00 | 7.5 | 30
당신은 다음 프리젠 테이션 계층에서 서식을 적용 할 수 있습니다.
Aaron Bertrand는 Choosing the wrong Data Type에 대한 기사에서 이것을 언급한다.그것은 상태 :
기간을
With SQL Server 2008, it may be tempting to store a duration in a column defined with the new TIME data type. This data type is not meant to store duration but actually a point in time. A problem with trying to store duration here is, what happens when your duration exceeds 24 hours? It would be much more useful to store the "duration" in two columns - StartTime and EndTime. You could add a third column which can be computed, calculating the duration in minutes or seconds or whatever makes sense. Your choice for the StartTime and EndTime columns could be TIME if you are reasonably confident that durations will always be less than 24 hours and will not cross any midnight boundaries, but more likely they should be SMALLDATETIME or DATETIME.
부칙
난 당신의 코드와 함께 할 것입니다 우선은 내부가 CTE 내에 가입 제거입니다 저장하는 시간을 사용 :
를
FROM AtdRecord t1
INNER JOIN AtdRecord t2
ON t1.EmplID = t2.EmplID
AND t1.RecDate = t2.RecDate
AND t1.RecTime < t2.RecTime
그것은 무의미한 일로, 하루에 각 직원에 대해 하나 이상의 레코드가 있다는 것을 보장합니다. 이는 having 절로 더 잘 수행 될 것입니다. 나 또한 give your tables meaningful aliases, 2 테이블 정말 필요한 것은 아니지만, 테이블이 많이있을 때 t1, t2, t3 등을 사용하면 빠르게 혼란스러워진다. 그래서 쿼리가된다 : 당신은 몇 가지 문장 부호와 예의를 사용한 경우
는
WITH Times AS
( SELECT emp.EmplID,
emp.EmplName,
InTime = MIN(atd.RecTime),
OutTime = MAX(atd.RecTime),
TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)),
OverTime = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)) - 480,
[DateVisited] = atd.RecDate
FROM AtdRecord atd
INNER JOIN HrEmployee emp
ON atd.EmplID = emp.EmplID
GROUP BY emp.EmplID, emp.EmplName, atd.RecDate
HAVING COUNT(atd.RecTime) > 1
)
SELECT t.EmplID,
t.EmplName,
t.InTime,
t.OutTime,
t.DateVisited,
t.TimeWorked,
OverTime,
FormattedTimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8),
FormattedOverTime = CASE WHEN t.OverTime < 0 THEN '-' ELSE '' END +
CONVERT(CHAR(5), DATEADD(MINUTE, ABS(t.OverTime), 0), 8)
FROM Times t;
Simplified Example on SQL Fiddle
좋을 것입니다. – flu
물론, 내 말은 다음 시간에 최선을 다할 것입니다 :) –