sql中的时间总和

时间:2011-07-05 17:06:06

标签: sql-server-2005

我有一张这样的桌子......

create table test
(
  dt datetime
)

在该表中,日期时间如下,

2011/02/02 12:55:00
2011/03/05 00:40:00
2011/02/03 00:12:00

我想计算总时数,mi,ss

在单个选择查询中不是sp。

如果有人知道请告诉我。

谢谢...

3 个答案:

答案 0 :(得分:2)

您可以将时间总和为秒,然后转换为小时,分钟和秒:

select TotalSeconds / 3600 as [Hours], (TotalSeconds % 3600) / 60 as [Minutes], (TotalSeconds % 3600) % 60 as [Seconds]
from
(
    select sum(datepart(hour, dt) * 3600) + sum(datepart(minute, dt) * 60) + sum(datepart(second, dt)) as TotalSeconds
    from test
) t

答案 1 :(得分:1)

假设总和不会超过999小时:

DECLARE @t TABLE(dt DATETIME);

INSERT @t SELECT '20110202 12:55'
    UNION SELECT '20110305 00:40'
    UNION SELECT '20110203 00:12';

WITH s AS
(
    SELECT s = SUM(DATEDIFF(SECOND, 
        DATEADD(DAY, 0, DATEDIFF(DAY, 0, dt)), dt))
    FROM @t
)
SELECT 
    s,
    hhmmss = RIGHT('000' + RTRIM(s/3600), 3)
     + ':' + RIGHT('00' + RTRIM((s % 3600) / 60), 2)
     + ':' + RIGHT('00' + RTRIM((s % 3600) % 60), 2)
FROM s;

但是,如果您实际存储的是持续时间,为什么不存储秒数而不是将数据楔入不合适的数据类型,这需要各种解决方法来正确处理?

答案 2 :(得分:1)

Declare @Table Table 
(
    DateTimeCol DateTime
)
insert into @Table values ( '2011/02/02 12:55:00')
insert into @Table values ('2011/03/05 00:40:00')
insert into @Table values ('2011/02/03 00:12:00')

;with CTE As
(
    --first of all find total seconds of datecolumn
    --sum all seconds
    Select SUM(
        (datepart(hour,DateTimeCol)*60*60)+(datepart(minute,DateTimeCol)*60)+(datepart(second,DateTimeCol))
    ) As TotalSecond    
    From @Table
)
--devides with 3600 to get the total hours and then to 60 to get total minutes
Select CONVERT(VARCHAR(10),TotalSecond/3600)+ '.' + 
CONVERT(VARCHAR(20),TotalSecond%3600/60) + '.' + 
CONVERT(VARCHAR(20),TotalSecond%3600%60) AS [Time] --Total of Time
From CTE