简体   繁体   English

在 SQL Server 中将时间间隔转换为十进制小时

[英]Convert time interval into decimal hours in SQL Server

I have a time interval in the format '88:52:57' I need to convert it into a decimal hours in the format 88.88我有一个格式为“88:52:57”的时间间隔,我需要将其转换为格式为 88.88 的小数小时

How can I do this?我怎样才能做到这一点?

I have the data initially loaded as a varchar我将数据最初加载为 varchar

You can use left, right and substring to extract the values and then do some calculations.您可以使用左、右和子字符串来提取值,然后进行一些计算。

declare @S varchar(8) = '88:52:57';

select left(@S, 2) + substring(@S, 4, 2)/60.0 + right(@S, 2)/60.0/60.0;

If you not always have two digit values you can use parsename to get the values instead.如果您并不总是有两位数的值,则可以使用 parsename 来获取值。

declare @S varchar(20) = '088:052:057';

select parsename(S.X, 3) + parsename(S.X, 2)/60.0 + parsename(S.X, 1)/60.0/60.0
from (select replace(@S, ':', '.')) as S(X)

Try it like this (best create an UDF from this):像这样尝试(最好从这里创建一个 UDF):

First I split the Time-Variable on its double dots via XML.首先,我通过 XML 在其双点上拆分时间变量。 The rest is simple calculation...剩下的就是简单的计算...

DECLARE @YourTime VARCHAR(100)='88:52:57';

WITH Splitted AS
(
    SELECT CAST('<x>' + REPLACE(@YourTime,':','</x><x>') + '</x>' AS XML) TimeParts
)
,TimeFract AS
(
    SELECT TimeParts.value('/x[1]','float') AS HourPart
           ,CAST(TimeParts.value('/x[2]','int') * 60 + TimeParts.value('/x[3]','int') AS FLOAT) Seconds
    FROM Splitted
)
SELECT HourPart + Seconds/3600   
FROM TimeFract

The result结果

88,8825

Try this, solution is based on conversions, making it safe, if the format is always (h)h:mi:ss:试试这个,解决方案基于转换,使其安全,如果格式始终为 (h)h:mi:ss:

DECLARE @S varchar(8) = '88:52:57';
SELECT
  CAST(REPLACE(left(@S, 2), ':', '') as int)+
  CAST(CAST(CAST('0:'+RIGHT(@S, 5) as datetime) as decimal(10,10)) * 24 as decimal(2,2))

Result:结果:

88.88

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM