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

SQL Convert Milliseconds to Days, Hours, Minutes

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

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

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 而不是 %

在 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

使用原生 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 位数字。也许存在提供类似日期对象的其他方法,我不知道。