Calculate Total Hours, Minutes and Seconds using T-SQL

I had recently posted about Convert Number to Hours and Minutes in SQL Server. I was writing a query where the table had three columns for Hours, Minutes and Seconds. I had to calculate the total hours, minutes and seconds for all the rows. The query had to also take care of rounding off every 60 minutes to an hour and every 60 seconds to a minute. Here’s the query if you have a similar requirement:

DECLARE @TT table
(
SNo int,
HoursSpent smallint,
MinutesSpent smallint,
SecondsSpent smallint
)

-- Create Sample Data
INSERT INTO @TT VALUES ( 1, 5, 20, 5);
INSERT INTO @TT VALUES ( 2, 2, 40, 22);
INSERT INTO @TT VALUES ( 3, 3, 33, 31);
INSERT INTO @TT VALUES ( 4, 6, 28, 52);
INSERT INTO @TT VALUES ( 5, 5, 1, 22);

SELECT TotMin / 3600 as TotalHours,
TotMin % 3600/60 as TotalMinutes,
TotMin % 60 as TotalSeconds
FROM
(
SELECT SUM(HoursSpent) * 3600 + SUM(MinutesSpent) * 60
+ SUM(SecondsSpent) as TotMin
FROM @TT
) temp

OUTPUT

Hours, minutes, seconds in T-SQL


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

No comments: