我有两列包含HH:MM
格式的时间。例如,column1的值为149:10,column2的值为110:20。
我想添加两列,我希望输出结果的格式为HH:MM
答案 0 :(得分:1)
由于给定的值无法存储到TIME
数据类型中,因此会抛出错误,如下所示:
DECLARE @TimeStamp1 AS TIME = '149:10'; SELECT @TimeStamp1;
因此,您的输入可能是varchar
。
我尝试了一种给定相同数据的方法:
DECLARE @TimeStamp1 AS VARCHAR(20) = '149:40';
DECLARE @TimeStamp2 AS VARCHAR(20) = '110:40';
SELECT CAST(
CAST(PARSENAME(REPLACE(@TimeStamp1, ':', '.'), 2) AS INT) +
CAST(PARSENAME(REPLACE(@TimeStamp2, ':', '.'), 2) AS INT) +
((CAST(PARSENAME(REPLACE(@TimeStamp1, ':', '.'), 1) AS INT) + CAST(PARSENAME(REPLACE(@TimeStamp2, ':', '.'), 1) AS INT)) / 60) AS VARCHAR (20))
+ ':' +
CAST((
(CAST(PARSENAME(REPLACE(@TimeStamp1, ':', '.'), 1) AS INT) +
CAST(PARSENAME(REPLACE(@TimeStamp2, ':', '.'), 1) AS INT)) % 60) AS VARCHAR (20)) AS Result;
Result
--------
260:20
答案 1 :(得分:0)
以下查询应该有效
declare @s1 varchar(max), @s2 varchar(max)
select @s1='149:50',@s2='110:50'
SELECT
CAST(
CAST(LEFT(@s1,CHARINDEX(':',@s1)-1) AS INT) +
CAST(LEFT(@s2,CHARINDEX(':',@s2)-1) AS INT) +
(CAST(RIGHT(@s1,LEN(@s1)-CHARINDEX(':',@s1)) AS INT) + CAST(RIGHT(@s2,LEN(@s2)-CHARINDEX(':',@s2)) AS INT))/60
as nvarchar)
+':'+
CAST(
(CAST(RIGHT(@s1,LEN(@s1)-CHARINDEX(':',@s1)) AS INT) +
CAST(RIGHT(@s2,LEN(@s2)-CHARINDEX(':',@s2)) AS INT))
%60
AS nvarchar)
答案 2 :(得分:0)
只是另一种选择
Declare @YourTable table (column1 varchar(25),column2 varchar(25))
Insert Into @YourTable values
('149:10','110:20')
Select A.*
,TotalTime = Format(B.Sec/3600 ,'0' )
+Format(B.Sec%3600/60,':00')
From @YourTable A
Cross Apply (values (
(3600*parsename(replace(column1,':','.'),2)+60*parsename(replace(column1,':','.'),1))
+(3600*parsename(replace(column2,':','.'),2)+60*parsename(replace(column2,':','.'),1))
)
) B (sec)
<强>返回强>
column1 column2 TotalTime
149:10 110:20 259:30