简体   繁体   English

在SQL中计算小时和分钟

[英]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. 我想从DateOfChange列的小时和分钟中找到旧状态更改和新状态更改之间的差异。

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 : Users

在此处输入图片说明

StatusLog : 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. 请注意,这是作为varchar数据类型返回的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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