0

我在 varchar/nvarchar 数据类型字段中求和时间时遇到麻烦。

这是我要求和的格式:(HH:mm:ss)

4

4 回答 4

0

干得好:

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

Live Demo

于 2013-10-14T08:37:47.973 回答
0
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*/
于 2013-10-14T08:48:26.567 回答
0

你也可以试试,

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

评论 :

  • 我建议您在日期或时间相关字段中使用 DateTime 或 Time 数据类型。
于 2013-10-14T08:53:36.727 回答
0

我已经想通了:

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
于 2013-10-15T06:54:13.257 回答