以hh:mm计算时差

时间:2018-01-12 10:34:12

标签: sql-server

我有这个查询,但我不确定使用什么功能,所以我可以通过这种“hh:mm”格式获得时差。有人可以帮忙吗?

SELECT        
EI.[FirstName]+' '+EI.[LastName] [EmployeeName], [Dpt].[FullName] [Department], [Desig].[FullName] [Designation],
FirstIN    = CAST(MIN([AttendanceTimeIn]) AS TIME), 
LastOUT    = CAST(MAX([AttendanceTimeOut]) AS TIME), 
HoursSpent = DATEDIFF(HOUR, CAST(MIN(AttendanceTimeIn) AS TIME), CAST(MAX(AttendanceTimeOut) AS TIME)),
CAST(COALESCE(AttendanceTimeIn, AttendanceTimeOut) AS DATE) [Date]

FROM [HRM].[tbl_Designation] [Desig], [HRM].[tbl_Department] [Dpt], [HRM].[tbl_EmployeeInfo] [EI]

FULL OUTER JOIN [HRM].[tbl_EmployeeAttendance] [Attendance] ON [Attendance].[EmpCode] = [EI].[ID] 

WHERE 

[Dpt].[ID] = [EI].[DeptCode] AND [Desig].[ID] = [EI].[DesignationCode]
AND
[EI].[RecordStatusCode] != '13'
AND 
CAST((GETDATE()-1) AS DATE) = CAST(ISNULL([AttendanceTimeIn], [AttendanceTimeOut]) AS Date)

GROUP BY
EI.[FirstName]+' '+EI.[LastName], [Dpt].[FullName], [Desig].[FullName], CAST(COALESCE(AttendanceTimeIn, AttendanceTimeOut) AS DATE)

3 个答案:

答案 0 :(得分:4)

也许你可以使用这样的东西:

declare @d1 datetime = '2018-01-11 23:40:18.010'
declare @d2 datetime = '2018-01-12 11:59:18.010'

SELECT CONVERT(VARCHAR(2),DATEPART(HOUR,@d2 - @d1)) + ':' + CONVERT(VARCHAR(2),DATEPART(MINUTE,@d2 - @d1));

答案 1 :(得分:1)

如果要忽略在持续时间内使用时间的概念,可以使用如下查询:

DECLARE @d1 DATETIME
DECLARE @d2 DATETIME

SELECT @d1 = GETDATE() - 1.465, @d2 = GETDATE()

SELECT
FirstIN    = @d1, 
LastOUT    = @d2, 
HoursSpent = CAST(DATEDIFF(HOUR, @d1, @d2) AS VARCHAR) + ':' + RIGHT('0' + CAST(DATEDIFF(MINUTE, @d1, @d2) % 60 AS VARCHAR), 2)

答案 2 :(得分:1)

让我们一步一步扩展:

declare
    @start datetime = getdate(),
    @end datetime = dateadd(second, getdate(), 5000)

-- datediff(hour, @start, @end) -> hour difference
-- dateadd(hour, @start, datediff(hour, @start, @end)) -> start + integer hour difference to get less-than-an-hour diff
-- datediff(minute, dateadd(hour, @start, datediff(hour, @start, @end)), @end) -> minute difference from there

select
    cast(datediff(hour, @start, @end) as varchar(2)) 
    + ':' 
    + cast(datediff(minute, dateadd(hour, @start, datediff(hour, @start, @end)), @end) as varchar(2)) as [hh:mm]