计算两个日期和总和之间的日期,然后转换为小时和分钟

时间:2014-11-19 05:27:25

标签: sql-server

我希望以小时和分钟获取日期差异并实现我在SQL Server中使用此查询:

Cast(SUM(DATEDIFF(second, fromtime, totime) / 60 / 60 % 24) as varchar(20)) + ' hours '
+CAST(SUM(DATEDIFF(second, fromtime, totime) / 60 % 60)as varchar(20))+' minutes '  as [TotalTime]

返回以下输出:

TotalTime
---------------------
16 Hours 120 Minutes 
3 Hours 90 Minutes  

但预期的输出是:

TotalTime
----------------------
18 Hours 0 Minutes 
4 Hours 30 Minutes.

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您的查询非常完美,您需要做的就是在上面写一个外部查询。像下面的东西

select case when t.minutes>60 then t.hours+(t.minutes/60) else t.hours end as hours,
       case when t.minutes>60 then t.minutes%60 else t.minutes end as minutes
from
(
select 
Cast(SUM(DATEDIFF(second, fromtime, totime) / 60 / 60 % 24) as varchar(20)) as hours
+CAST(SUM(DATEDIFF(second, fromtime, totime) / 60 % 60)as varchar(20)) as minutes
from tablename
)as t