Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Sum time display issue

Tags:

sql

sql-server

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
like image 596
Crezzer7 Avatar asked Aug 10 '26 03:08

Crezzer7


2 Answers

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.

like image 52
HoneyBadger Avatar answered Aug 13 '26 07:08

HoneyBadger


Right('0'+cast(yourvalue as varchar(2)),2)
like image 32
pacreely Avatar answered Aug 13 '26 08:08

pacreely