简体   繁体   中英

Calculating hours and minutes in sql

I have query:

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

在此处输入图片说明

I want to find the difference between old status change and new status change in terms of hours and minutes from DateOfChange Column.

ie

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

I have written this query:

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

But its calculating just hours. Not minutes as I mentioned above.

I have used following tables in my joins:

Users :

在此处输入图片说明

StatusLog :

在此处输入图片说明

Please help me.

Try this:

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

The first expression will get the difference in hours, and the third the difference in minutes. Note that this is returned as a varchar data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM