如何使用datediff函数显示日,小时,分钟和秒

时间:2015-07-31 12:47:44

标签: sql sql-server sql-server-2008

我有一个记录:

Depart_dt               Arrived_dt 
10/1/2013 6:15:00 AM    10/1/2013 7:25:00 AM

根据我的计算,arrived_dtDepart_dt之间为0天,1小时和10分钟。如何显示如下结果:

Day   Hour  Minute  Second
0     1     10      0

2 个答案:

答案 0 :(得分:3)

您可以在DATEDIFF()函数的输出上使用模数除法:

SELECT DATEDIFF(second,Depart_dt,Arrived_Dt)/(60*60*24) AS Day
      ,DATEDIFF(second,Depart_dt,Arrived_Dt)/(60*60)%24 AS Hour
      ,DATEDIFF(second,Depart_dt,Arrived_Dt)/(60)%60 AS Minute
      ,DATEDIFF(second,Depart_dt,Arrived_Dt)%60 AS Second
FROM Table1

演示:SQL Fiddle

答案 1 :(得分:1)

select 
datediff(second,depart_dt, arrived_dt)/86400 as Day,
datediff(second,depart_dt, arrived_dt)/3600%24 as Hour,
datediff(second,depart_dt, arrived_dt)/60%60 as Minute,
datediff(second,depart_dt, arrived_dt)%60 as Second
from yourtable

将日,小时和分钟转换为精确度的秒数。

SQL小提琴:http://sqlfiddle.com/#!6/c6c63/1