SQL中的十进制(时间)之和

时间:2014-12-12 12:59:37

标签: sql sql-server sql-server-2008

我的表有4行,值为

6.30
6.30
6.30
6.30

现在我想对列进行求和。

我试过下面的代码

Select SUM(Time) from #temp

但我得到了25.20作为一个罢工。

但是上面的值是hh.mm

我希望结果为26。

我如何在sql中实现这一点。?

5 个答案:

答案 0 :(得分:4)

试试这个:

select sum(floor(time)) + sum(time - floor(time)) * 100.0/60

这会分别添加小时和分钟部分。

结果的解释为十进制小时。如果您想将其转换回小时和分钟:

select floor(sum(floor(time)) + sum(time - floor(time)) * 100.0/60) +
       ((sum(floor(time)) + sum(time - floor(time)) * 100.0/60) % 1) * 60.0/100

答案 1 :(得分:1)

只需按分钟数记录数据库中的值?即1Hr 20min = 80

答案 2 :(得分:1)

我要修改戈登的建议:

CREATE TABLE #test (time DECIMAL(18,2))
INSERT INTO #test (time) VALUES (4.2)
INSERT INTO #test (time) VALUES (4.2)
INSERT INTO #test (time) VALUES (4.2)
INSERT INTO #test (time) VALUES (4.2)

select CONVERT(DECIMAL(18,2),
    floor(sum(floor(time)) + sum(time - floor(time)) * 100.0/60)/1 +
       ((sum(floor(time))/1 + sum(time - floor(time)) * 100.0/60) % 1) * 60.0/100
    )
FROM #test

如果您要求总和的值不等于确切的小时数,那么它就会完成。 (对于上述数据,此SQL将为您提供17.20而不是17,以满足您的要求(17小时20分钟)。对于原始问题中的数据,两个答案将返回相同的值)。这将保留全部时间并将数据转换回DECIMAL(18,2)。

答案 3 :(得分:0)

SELECT ceiling(sum(time))
FROM   #temp

答案 4 :(得分:0)

您可以使用内置函数time_to_sec然后使用sec_to_time。这是mysql中的代码:

create temporary table tmp (t1 time);
insert tmp values('6:30');
insert tmp values('6:30');
insert tmp values('6:30');
insert tmp values('6:30');
select sec_to_time(sum(time_to_sec(t1))) from tmp

产生:'26:00:00'