I want to calculate the Sum of the Field which has Time DataType.
My Table is Below:
TableA:
TotalTime
-------------
12:18:00
12:18:00
Here I want to sum the two time fields.
I tried the below Query
SELECT CAST(
DATEADD(MS, SUM(DATEDIFF(MS, '00:00:00.000',
CONVERT(TIME, TotalTime))), '00:00:00.000'
) AS TOTALTIME)
FROM [TableA]
But it gives the Output as
TOTALTIME
-----------------
00:36:00.0000000
But My Desired Output would be like below:
TOTALTIME
-----------------
24:36:00
How to get this Output?
You could sum the total number of seconds, or datediff(second,0,datecolumn)
. You can format that as a time string with some math. For example, the total number of minutes is totalseconds / 60 % 60
. For example:
select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from TestTable
Working code at SQL Fiddle.
24:36 is the same as 00:36(Next day)
Your query is working fine the results are correct,
24:36 is the time 00:36 for next day.
You can display maximum 24 hrs. You are not using any day thats why every 24 hrs =0 hrs for next day.
Just change the column values and you can see that.
It would be a tad longwinded, but if you wanted to avoid the day rollover but you could split the second TIME into constituent datepart()'s and then add those on? (even display as a varchar if it's necessary to have an hour value greater than 24.
TRY THIS.
SELECT
CONVERT(VARCHAR(MAX),SUM(DATEPART(HH,CAST(YOUR_FIELD AS DATETIME)))+
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))/60) +
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60 +
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))/60) + ':' +
RIGHT('00' + CONVERT(VARCHAR(MAX),
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60+
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))%60),2) + ':' +
RIGHT('00' + CONVERT(VARCHAR(MAX),SUM(DATEPART(SECOND,
CAST(YOUR_FIELD AS DATETIME)))%60),2) AS YOUR_FIELD
FROM YOUR_TABLE