我在 varchar/nvarchar 数据类型字段中求和时间时遇到麻烦。
这是我要求和的格式:(HH:mm:ss)
干得好:
create table tblTime (dt datetime)
insert tblTime values
('00:25:00'),
('00:20:00')
这是计算:
Select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from tblTime
输出:0:45:00
declare @time1 varchar(8) = '00:25:00';
declare @time2 varchar(8) = '00:20:00';
select CONVERT(varchar(8),
DATEADD (SECOND ,
(CONVERT(int, LEFT(@time1, 2))*60*60 /* hours in seconds*/
+ CONVERT(int, substring(@time1,4,2)*60) /* minutes in seconds*/
+ CONVERT(int, RIGHT(@time1, 2)))/* seconds only */
, '19000101 ' + @time2
)
,108)/* convert back to time format*/
你也可以试试,
create table timeSum (value1 varchar(50), value3 varchar(50))
insert into timeSum values ('00:45', '00:10')
计算
select Convert(Varchar,(Convert(DateTime,Value1 )+Convert(DateTime,value3)),114) as TotalTime from timeSum
输出:00:55:00:000
评论 :
我已经想通了:
select convert(decimal(18, 2), convert(decimal(18, 2), ppt.hour) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.minute/ 60)) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.second / 3600))) AS Hours, ppt.[column] from (select SUM(convert(decimal(2),left([column], 2))) AS hour, SUM(convert(decimal(2), left(right([column], 5), 2))) AS minute, SUM(convert(decimal(2), right([column], 2))) AS second, [column] FROM [table] GROUP BY [column]) AS ppt