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 2008 Forums
 Transact-SQL (2008)
 Working with increments of time

Author  Topic 

nerdygirl61
Starting Member

21 Posts

Posted - 2011-12-14 : 19:24:23
I am working with increments of time stored in a decimal format, so an hour and forty minutes would be stored as 1.40. I need to know how to add these correctly. For example in adding 1.45, 1.30, 1.25 I would need them to calculate to 4.40 (four hours and forty minutes) instead of 4. Any suggestions on how to tweak these prior to summing them so they come out corretly?

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-12-14 : 19:54:52
Many people on this forum would advise you to store time as TIME or DATETIME data types. However, sometimes, you have to work with what you have, so here is an example of how I would do it.
CREATE TABLE #tmp(val DECIMAL(9,2));
INSERT INTO #tmp VALUES (1.45),(1.3),(1.25);

WITH A AS
(
SELECT
SUM(DATEPART( HOUR, CAST(REPLACE(val,'.',':') AS DATETIME)) ) * 60 +
SUM(DATEPART( MINUTE, CAST(REPLACE(val,'.',':') AS DATETIME) ) ) TotalMinutes
FROM
#tmp
)
SELECT TotalMinutes/60 + TotalMinutes%60/100. FROM A;

DROP TABLE #tmp;
If you are on SQL 2008, TIME datatype instead of DATETIME datatype can be used.

It may be easier to do this with simple floats and floors and modulos. But there is something intangible that I like about using date/time data types when working with date and time, that is why I used this approach.
Go to Top of Page

nerdygirl61
Starting Member

21 Posts

Posted - 2011-12-14 : 20:28:53
Thank YOU!
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-12-14 : 20:35:31
or you can convert your time to minutes, sum it and convert back

(floor( time_col ) * 60) + ( time_col * 100 % 100)



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -