I have found the following formula on stack overflow which has helped me sum up time values, which works brilliant after tweaking it slightly:
SELECT CAST(t.TotalHours/3600 AS VARCHAR(2)) + ':'
+ CAST(t.TotalHours%3600/60 AS VARCHAR(2)) + ':00'
FROM ( SELECT SUM(DATEDIFF(S, '00:00', WorkingHours)) AS TotalHours
FROM workhour) t
from SQL How to sum times from Time datatype columns in hh:mm:ss
However I am now having an issue in terms of formatting. When I run this query on my data, it returns the time sum in this format: HH:M:SS (32:0:00)
My Data:
WorkingHours
05:30
06:00
05:30
08:00
07:00
Expected Output:
TotalHours
32:00:00
As you will notice, my data does not consist of seconds, so I have added that at the end as a string. Its the minutes that appear to be causing me an issue.
Question:
Is there a way to tweak the above forumla so that I can get the total to display as HH:MM:SS -> 32:00:00
NOTE: This occurs when the minutes field returns 0, or has a value of less than 10...
Thankyou for the help in advance. I am using SQL Server 2016 Data Center, and have the data stored in my table as a varchar in the format HH:MM, called WorkingHours.
Working Answer:
SELECT CAST(t.TotalHours/3600 AS VARCHAR(2)) + ':' +
RIGHT('000' + CAST (t.TotalHours%3600/60 AS VARCHAR(2)), 2) + ':00'
FROM ( SELECT SUM(DATEDIFF(S, '00:00', TotalHours)) AS TotalHours
FROM workhour) t
You can use:
RIGHT('000' + CAST (t.time_sum%3600/60 AS VARCHAR(2)), 2)
This will take the 2 right-most characters of the concatenation of '000' and the calculated minutes. So if your minutes are less then 10, a 0 is added in front. Resulting in 01 - 60.
I always use more 0 than I'm going to need, just because it doesn't matter, and I'll always be safe.
Right('0'+cast(yourvalue as varchar(2)),2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With