SQL将毫秒转换为天,小时,分钟

时间:2017-07-17 14:23:46

标签: sql sql-server tsql sql-server-2017

我需要将毫秒值85605304.3587转换为0d 18h 21m的值。 不知道如何开始,有没有类似于SQL中的TimeSpan,就像在C#中那样?

3 个答案:

答案 0 :(得分:8)

您可以明确地进行计算。我认为是:

select floor(msvalue / (1000 * 60 * 60 * 24)) as days,
       floor(msvalue / (1000 * 60 * 60)) % 24 as hours,
       floor(msvalue / (1000 * 60)) % 60 as minutes

注意:有些数据库使用mod而不是%

答案 1 :(得分:1)

使用原生date & time functions,可能:

SELECT
    AsDateTime = DATEADD(MILLISECOND, 85605304, 0)
  , AsDateTime2 = DATEADD(NANOSECOND, 7 * 100, DATEADD(MICROSECOND, 358, DATEADD(MILLISECOND, 85605304, CONVERT(datetime2, CONVERT(datetime, 0)))))
-- Incorrect datetime2 approach I initially did, has some precision loss, probably due to datetime's millisecond issue with 0's, 3's, and 7.'s
--SELECT DontDoThis = DATEADD(NANOSECOND, 7 * 100, DATEADD(MICROSECOND, 358, CONVERT(datetime2, DATEADD(MILLISECOND, 85605304, 0))))

datetime仅涵盖超过秒的3位数,而datetime2将保持7位数。也许存在其他类似日期对象的方法,我不知道。

答案 2 :(得分:0)

在MS SQL SERVER中,您可以使用下一个代码:

with cte as (
    select cast(85605304.3587 as int) / 1000 / 60 as [min]
), cte2 as (
    select 
        cast([min] % 60 as varchar(max)) as minutes,
        cast(([min] / 60) % 24 as varchar(max)) as hours,
        cast([min] / (60 * 24) as varchar(max)) as days
    from cte
)
select concat(days, 'd ', hours, 'h ', minutes, 'm') as tm
from cte2