以 HHH:MM:SS 格式 (Nvarchar) 将天数转换为小时数

Convert days to hours in HHH:MM:SS Format (Nvarchar)

我有一个 table,我需要将 2.6 天或 5 天、3.2 天等转换为小时。由于它是 24 小时以上的格式,我知道我需要转换为 nvarchar。我搜索了很多论坛,但我无法确切地知道我该怎么做,我想我必须将这天数转换为秒数,然后再从秒数转换为 nvarchar 格式。有人知道吗?

谢谢大家:)

您似乎认为需要使用 nvarchar。但事实并非如此。如果您可以将小时数存储为十进制。解决方法很简单

hours = days * 24

如果您想将其分解为小时、分钟和秒,您需要将其转换为秒。一天有24小时,一小时有60分钟,一分钟有60秒。

seconds = days * 24 * 60 * 60 

获得秒数后,您可以将除法运算符 (/) 与模运算符 (%) 一起使用。如果您将天数存储为十进制 (3,1) 您将不必担心秒数,因为分辨率太低了。

select 
 days
 ,CAST(days * 24 * 60 * 60 as int) as totalseconds --days converted to full seconds
 ,CAST(days * 24 * 60 as int) as totalminutes --days converted to full minutes
 ,CAST(days * 24  as int) as totalfullhours --days converted to full hours
 ,CAST(days * 24 * 60 as int) % 60 as remainingminutes -- since the row above contains full hours, we need to find out how many minutes are in the split hours f ex 0.2 hours
 ,CAST(days * 24 * 60 * 60 as int) % 60 as remainingseconds -- this will always be 0 because of your precision
from YourTable

如果您仍希望将结果作为单个字符串列 (HH::mm),它将是

select 
     CAST(CAST(days * 24  as int) as varchar(10)) + ':' + RIGHT('0'+CAST(CAST(days * 24 * 60 as int) % 60 as varchar(10)),2) 
    from YourTable