如何在 SQL 服务器 2008 中将负时间跨度转换为正时间跨度
How to convert negative time span to positive in SQL server 2008
我有这样一种情况,其中一些持续时间是负数格式并在 SQL 数据库中作为字符串存储为
-06:34:41
其中一些将采用正格式
02:00:00
和
01:00:00
现在我需要使用 SQL Server 2008 在 select 查询中 add/sum 这些持续时间,这样结果将是
-03:34:41
然后在计算之后我需要将其恢复为字符串格式。在此先感谢。
这对我有用:
declare @timevalues table
(
timestring NVARCHAR(10)
)
insert into @timevalues
values
('-06:34:41'),
('02:00:00'),
('01:00:00')
;
with cte
as
( select case when left(timestring,1)='-' then -1 else 1 end as multiply,
right(timestring,8) as timestring,
--get hours in seconds:
DATEPART(HOUR,right(timestring,8)) * 3600 AS h_in_s,
--get minutes in seconds:
DATEPART(MINUTE,right(timestring,8)) * 60 AS m_in_s,
--get seconds:
DATEPART(SECOND,right(timestring,8)) AS s
from @timevalues
)
select case when sum((c.h_in_s + c.m_in_s + c.s) * multiply) < 0
then '-' + CONVERT(varchar,DATEADD(s,ABS(sum((c.h_in_s + c.m_in_s + c.s) * multiply)),0),114)
else CONVERT(varchar,DATEADD(s,sum((c.h_in_s + c.m_in_s + c.s) * multiply),0),114)
end as new_time_string
from cte c
输出为:
这基本上是做什么的:在 cte 中,我将所有时间分量都设置为秒,因此我们可以对秒求和 (h_in_s + m_in_s + s
)。获得秒数总和后,您需要将秒数转换为时间字符串。这是通过在我们的表达式中添加 0 秒来完成的(例如 DATEADD(s,15300,0)
)。使用格式代码 114 和 voilà
将其转换为 varchar
我有这样一种情况,其中一些持续时间是负数格式并在 SQL 数据库中作为字符串存储为
-06:34:41
其中一些将采用正格式
02:00:00
和
01:00:00
现在我需要使用 SQL Server 2008 在 select 查询中 add/sum 这些持续时间,这样结果将是
-03:34:41
然后在计算之后我需要将其恢复为字符串格式。在此先感谢。
这对我有用:
declare @timevalues table
(
timestring NVARCHAR(10)
)
insert into @timevalues
values
('-06:34:41'),
('02:00:00'),
('01:00:00')
;
with cte
as
( select case when left(timestring,1)='-' then -1 else 1 end as multiply,
right(timestring,8) as timestring,
--get hours in seconds:
DATEPART(HOUR,right(timestring,8)) * 3600 AS h_in_s,
--get minutes in seconds:
DATEPART(MINUTE,right(timestring,8)) * 60 AS m_in_s,
--get seconds:
DATEPART(SECOND,right(timestring,8)) AS s
from @timevalues
)
select case when sum((c.h_in_s + c.m_in_s + c.s) * multiply) < 0
then '-' + CONVERT(varchar,DATEADD(s,ABS(sum((c.h_in_s + c.m_in_s + c.s) * multiply)),0),114)
else CONVERT(varchar,DATEADD(s,sum((c.h_in_s + c.m_in_s + c.s) * multiply),0),114)
end as new_time_string
from cte c
输出为:
这基本上是做什么的:在 cte 中,我将所有时间分量都设置为秒,因此我们可以对秒求和 (h_in_s + m_in_s + s
)。获得秒数总和后,您需要将秒数转换为时间字符串。这是通过在我们的表达式中添加 0 秒来完成的(例如 DATEADD(s,15300,0)
)。使用格式代码 114 和 voilà