varchar / nvarchar数据类型字段中的SUM时间

时间:2013-10-14 08:25:25

标签: sql time sum varchar nvarchar

我在varchar / nvarchar数据类型字段中遇到SUM时间问题。

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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*/

答案 2 :(得分: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 
  

Out Put :00:55:00:000

备注:

  • 我建议您在Date或Time相关字段中使用DateTime或Time数据类型。

答案 3 :(得分: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