日期:2014-05-18  浏览次数:20641 次

Sum如何统计Char类型的字段
现在有一个表的字段里边存储的数据格式如下
TimeLen
--------
08:32:33
00:00:06
00:00:30
00:00:13
00:00:15
00:00:08
00:00:54
00:00:48
00:00:33

我想用Sum(TimeLen)求所有时间加在一起的值,求不了的,老报这个错“运算不能以   char   类型做为参数”,我把数据类型改为DateTime也不行的,烦死了,有没有高手给说一下解决办法呀,不盛感谢!!!


------解决方案--------------------
declare @t table(TimeLen char(8))
insert into @t select '08:32:33 '
insert into @t select '00:00:06 '
insert into @t select '00:00:30 '
insert into @t select '00:00:13 '
insert into @t select '00:00:15 '
insert into @t select '00:00:08 '
insert into @t select '00:00:54 '
insert into @t select '00:00:48 '
insert into @t select '00:00:33 '

select convert(char(8),dateadd(ss,sum(datediff(ss,0,cast(TimeLen as datetime))),0),108) from @t

/*
--------
08:36:00
*/
------解决方案--------------------
楼上快啊,我刚试验成功就有人写出来了
------解决方案--------------------
用datediff() 得出差多少秒(与1900-1-1),SUM起来,再用dateadd加上SUM的的秒数
就是楼上的了
------解决方案--------------------
TimeLen
一个语句太长,建议先建个视图,分部分统计,然后再计算进位(应该是60进制吧?):

-- 创建视图,分部分求和
Create View viewTimeLen As
Select Sum(Convert(int, SubString(TimeLen, 1, 2))) as H,
Sum(Convert(int, SubString(TimeLen, 4, 2))) as M,
Sum(Convert(int, SubString(TimeLen, 7, 2))) as S
From xxTable

-- 再创建个视图,按60进制进位
Create View viewTimeLen60 As
Select H + M / 60 + S / 3600 as H,
M % 60 + (S % 3600) / 60 as M,
S % 60 as S
From viewTimeLen

-- 查询时从视图中查询
Select Convert(varchar(2), H) + ': ' + Convert(varchar(2), M) + ': ' + Convert(varchar(2), S) as TimeLen
From viewTimeLen60

这样查询出结果不是每段两位,如10:8:9不会是10:08:09。如果要达到后一个效果,可以考虑用case语句。

总结:这么麻烦,都是因为你数据库设计的原因。
------解决方案--------------------
SUM(TimeLen) 换成
convert(char(8),dateadd(ss,sum(datediff(ss,0,cast(TimeLen as datetime))),0),108)