在sql中计算小时和分钟

时间:2014-04-21 05:33:27

标签: sql database sql-server-2008-r2

我有疑问:

SELECT    
    MemberId,  
    FirstName,LastName,  
    [DateOfChange]        
    ,(select title from StatusList where idStatus=[OldStatus]) as [OldStatus]  
    ,(select title from StatusList where idStatus=[NewStatus]) as [NewStatus]  
FROM 
    [statusLog] , Users 
WHERE
    statusLog.IdUser = Users.IdUser

enter image description here

我想在DateOfChange列的小时和分钟方面找出旧状态更改与新状态更改之间的区别。

DateOfChange             OldStatus          NewStatus     DiffernceInTime
-------------------------------------------------------------------------    
2014-04-04 16:15:20       Patrol              OnCall          ---
2014-04-04 17:20:20       OnCall              Patrol         1:05
2014-04-04 18:30:20       Patrol              Available      1:10

我写了这个查询:

SELECT 
   [users].MemberId,
   [users].FirstName,
   [users].LastName,
   thisLog.DateOfChange,
   statusList1.title as OldStatus,
   statuslist2.title as NewStatus,
   (SELECT TOP 1 DATEDIFF(hour, lastLog.DateOfChange, thisLog.DateOfChange)
    FROM [dbo].[statusLog] lastLog 
    WHERE lastLog.DateOfChange < thisLog.DateOfChange
    ORDER BY DateOfChange DESC) AS HoursSinceLastChange
FROM 
   [dbo].[statusLog] thisLog
INNER JOIN 
   [users] ON [users].IdUser = thisLog.IdUSer
INNER JOIN 
   StatusList statusList1 ON statusList1.idStatus = thisLog.OldStatus
INNER JOIN 
   StatusList statusList2 on statusList2.idStatus = thisLog.Newstatus
ORDER BY 
   DateOfChange DESC

但它的计算只需几个小时。不是我上面提到的分钟。

我在联接中使用了以下表格:

Users

enter image description here

StatusLog

enter image description here

请帮帮我。

1 个答案:

答案 0 :(得分:1)

试试这个:

cast(datediff(minute,@start,@end)/60  as varchar)
+':'
+right('00'+cast(datediff(minute,@start,@end)%60 as varchar),2) [DifferenceInTime]

第一个表达式将以小时为单位获得差异,第三个表达式将以分钟为单位获得差异。请注意,这是以varchar数据类型返回的。