I have 2 columns in my table in sql server – [Occurrence Time (NT)] and [Clearance Time(NT)] having the format yyyy-mm-dd hh:mm:ss and a third column [Outage Duration] with the format hh:mm:ss
[Identifier] | [Occurrence Time(NT)] | [Clearance Time(NT)] | [Outage Duration]
4 | 2014-12-28 15:06:33.000 | 2014-12-28 15:18:18.000 | 00:11:45.000
Outage duration is calculated as the difference of [Occurrence Time (NT)] and [Clearance Time(NT)] Currently my code to do this is as follows :
select distinct a.[Identifier]
,a.[Occurrence Time(NT)]
,a.[Clearance Time(NT)]
,cast((cast(a.[Clearance Time(NT)] as datetime) - cast(a.[Occurrence Time(NT)]as datetime)) as time )
as [Outage Duration]
from final_report_2 a
The cast is just a failsafe as both the columns are already datetime. This code works for all cases where [Occurrence Time (NT)] and [Clearance Time(NT)] fall on the same day i.e. the outage is within 24 hours
For e.g in above row no. 4 both have 28th as the day and thus the outage is calculated correctly.
But the outage duration is wrongly calculated in case of different days.
2678 | 2014-12-28 12:50:04.000 | 2014-12-31 23:59:59.000 | 11:09:55.000
In row 2678 the time should be 83:09:55 instead of 11:09:55.
So I need to factor in the difference of the days as well and then calculate the [Outage duration] in hh:mm:ss format.
One of the possible ways to do this is as follows :
(23:59:59 – 12:50:04) + 00:00:01 + ((31-28-1)*24):00:00 + 23:59:59
where the first part calculates the time of the first day , then the second part calculates the no. of whole days in between the [Occurrence Time (NT)] and [Clearance Time(NT)] and multiplies it by 24 and the final part represents the time of the final day.
How can I implement the above in sql server ? Can it be done using DATEPART or DATEADD functions?