Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Working with TIME

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2005-02-28 : 07:50:46
Rick writes "I have several records containg time values in hh:mm:ss format. I need to add all the times together to get a total elapsed time.

Example:

1 00:05:11
2 00:04:35
3 01:57:10

Total 02:06:56

This is SQL2000 SP3 on Win2003

Thanks"

tkeith
Starting Member

9 Posts

Posted - 2005-02-28 : 18:16:11
Here's one way you could do it:


DECLARE @timetable TABLE(_id int IDENTITY, timeval nvarchar(10))
DECLARE @hours int
, @minutes int
, @seconds int

INSERT INTO @timetable
SELECT '00:05:11'
UNION SELECT '00:04:35'
UNION SELECT '01:57:45'
UNION SELECT '02:52:28'

/* Use SUBSTRING and CHARINDEX to seperate hours, minutes,
and seconds, then calculate the total time */

SELECT @hours = hours + FLOOR((minutes + FLOOR(seconds/60))/60)
, @minutes = minutes + FLOOR(seconds/60) - (FLOOR((minutes + FLOOR(seconds/60))/60) *60)
, @seconds = seconds - (FLOOR(seconds/60) * 60)
FROM (
SELECT SUM(CAST(SUBSTRING(timeval,1,CHARINDEX(':',timeval)-1) AS int)) AS hours
, SUM(CAST(SUBSTRING(timeval,CHARINDEX(':',timeval)+1,2) AS int)) AS minutes
, SUM(CAST(SUBSTRING(timeval,CHARINDEX(':',timeval)+4,2) AS int)) AS seconds
FROM @timetable
) t

SELECT CASE WHEN LEN(@hours) <= 2 THEN RIGHT('00' + CAST(@hours as varchar(5)), 2)
ELSE CAST(@hours as varchar(5)) END + ':'
+ RIGHT('00' + CAST(@minutes as varchar(5)), 2) + ':'
+ RIGHT('00' + CAST(@seconds as varchar(5)), 2) AS [Total Time]
Go to Top of Page

tkeith
Starting Member

9 Posts

Posted - 2005-02-28 : 18:53:55
Alternatively, you could use the following:


/* Convert to dates, sum the DATEDIFFs, then convert back to hh:mm:ss */

SELECT @hours = FLOOR(FLOOR(seconds/60)/60)
, @minutes = FLOOR(seconds/60) - (FLOOR(FLOOR(seconds/60)/60) * 60)
, @seconds = seconds - (FLOOR(seconds/60) * 60)

FROM (
SELECT SUM(-1 * DATEDIFF(ss,CAST(timeval as datetime),CAST('00:00:00' as datetime))) AS seconds
FROM @timetable
) t

SELECT CASE WHEN LEN(@hours) <= 2 THEN RIGHT('00' + CAST(@hours as varchar(5)), 2)
ELSE CAST(@hours as varchar(5)) END + ':'
+ RIGHT('00' + CAST(@minutes as varchar(5)), 2) + ':'
+ RIGHT('00' + CAST(@seconds as varchar(5)), 2) AS [Total Time]
Go to Top of Page

nosepicker
Constraint Violating Yak Guru

366 Posts

Posted - 2005-02-28 : 19:28:47
Here's another way:

SELECT CONVERT(varchar, DATEADD(s, SUM(DATEDIFF(s, 0, CONVERT(datetime, YourTimeColumn))), 0), 108) FROM YourTable
Go to Top of Page

tkeith
Starting Member

9 Posts

Posted - 2005-02-28 : 19:38:23
Oh I like that one. I knew there had to be a simpler way.
Go to Top of Page
   

- Advertisement -