March 09, 2010

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:

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
SELECT SUM(HoursSpent) * 3600 + SUM(MinutesSpent) * 60
+ SUM(SecondsSpent) as TotMin
) temp


Hours, minutes, seconds in T-SQL

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

No comments: