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

No comments:

Post a Comment