'Subtracting Time Intervals in SQL

I have a table with 2 rows of time intervals. The data is stored as a varchar containing the hour and minutes, like the sample data below. I need to find a way to subtract the first column of data from the second and keep it as a time interval format. As seen below in the following table, I want to subtract colB from colA, to get the numbers in desiredOutcome displayed in the same format.

colA colB desiredOutcome
10:30 1:30 9:00
1:50 1:47 0:03
20:10 15:15 4:55
250:10 50:05 200:05

Any and all help is greatly appreciated

EDIT: To clarify, these are time intervals, not times of the day. I have added more data to the table to show this, it is the amount of time taken in hours and minutes to perform a task. Also, the data is stored in varchar, but I can just use CAST() to change that.



Solution 1:[1]

Will say would have recommended storing this as simple minutes using a data type like int, then format for the user to your HH:MM format. It would make calculations like this a lot easier.

So for example instead of storing 250:10, would have stored it as 15010 minutes

Below I converted your HH:MM time lengths to minutes, did the calculation, and then formatted it back again.

Calculating Difference Between HH:MM Time Lengths

DROP TABLE IF EXISTS #Interval
CREATE TABLE #Interval (ID INT IDENTITY(1,1) PRIMARY KEY, colA Varchar(10),colB Varchar(10))

INSERT INTO #Interval
VALUES
('10:30','1:30')
,('1:50','1:47')
,('20:10','15:15')
,('250:10','50:05')

SELECT *
    ,DesiredOutcome = CONCAT(FLOOR(DeltaInMinutes/60.0),':',FORMAT(DeltaInMinutes % 60,'0#'))
FROM #Interval AS A
/*Find the colons*/
CROSS APPLY (
    SELECT idxA = NULLIF(CHARINDEX(':',A.ColA),0)
        ,idxB = NULLIF(CHARINDEX(':',A.ColB),0)
) AS B
/*Break up into hours and minutes*/
CROSS APPLY(
    SELECT HrsA =   ISNULL(SUBSTRING(A.ColA,0,idxA),0)
        ,HrsB =     ISNULL(SUBSTRING(A.ColB,0,idxB),0)
        ,MinutesA = ISNULL(SUBSTRING(A.ColA,idxA+1,100),0)
        ,MinutesB = ISNULL(SUBSTRING(A.ColB,idxB+1,100),0)
) AS C
/*Find total duration in minutes*/
CROSS APPLY (
    SELECT TotalMinutesA = (HrsA * 60) + MinutesA
    ,TotalMinutesB = (HrsB * 60) + MinutesB
) AS D
/*Calculate delta*/
CROSS APPLY (
    SELECT DeltaInMinutes = TotalMinutesA - TotalMinutesB
) AS E

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1