Monday, February 27, 2012

How can I get the sum of hours stored in a datetime datatype

I need to get (In a select statement, for a stored procedure) the SUM of hours stored in a datetime column (column name TaskHours). For example; (1/1/1900 3:30:00 AM, 1/1/1900 5:15:00 AM, 1/1/1900 4:45:00 AM) (3:30 + 5:15 + 4:45) this should sum to 13.5 hours.

(not 12.90)

I appreciate your help!

try this logic:

print

(datediff(minute,convert(datetime,'1/1/1900',101),convert(datetime,'1/1/1900 3:30:00 AM',101))+
datediff(minute,convert(datetime,'1/1/1900',101),convert(datetime,'1/1/1900 4:45:00 AM',101))+
datediff(minute,convert(datetime,'1/1/1900',101),convert(datetime,'1/1/1900 5:15:00 AM',101)))/60.00

thanks

|||

That came up with the correct total. But how would I sum a column of these, not hard coding them?

tblVTasks (TaskHours)

|||

try this:

createTable #time( userIDint,

tt

datetime)

insert

Into #timevalues(1,'1/1/1900 3:30:00 AM')

insert

Into #timevalues(1,'1/1/1900 4:45:00 AM')

insert

Into #timevalues(1,'1/1/1900 5:15:00 AM')

insert

Into #timevalues(2,'1/1/1900 1:30:00 AM')

insert

Into #timevalues(2,'1/1/1900 2:45:00 AM')

insert

Into #timevalues(2,'1/1/1900 2:15:00 AM')

select

userID,ttfrom #time

select

userID,datediff(minute,convert(datetime,'1/1/1900',101),tt)from #time

select

userID,SUM(datediff(minute,convert(datetime,'1/1/1900',101),tt))/60.00from #time

group

by userID

drop

Table #time

I hope that it should be all you need.

Good luck

No comments:

Post a Comment