将天转换为小时hhh:mm:ss格式(nvarchar)

js5cn81o  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(414)

我有一个表格,我需要转换,例如2.6天或5天,3.2天等小时。因为它是24小时以上的格式,我知道我需要转换为nvarchar。我搜索了很多论坛,但我看不出具体怎么做,我想我必须把这几天转换成秒,然后再从秒转换成nvarchar格式。有人知道吗?
thx全部:)

33qvvth1

33qvvth11#

你似乎认为你需要使用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

相关问题