sum of date difference of different id in sql <p>I have user defined function like this:</p> <pre><code>create FUNCTION dbo.FormattedTimeDiff (@Date1 DATETIME, @Date2 DATETIME) RETURNS VARCHAR(10) AS BEGIN DECLARE @DiffSeconds INT = sum(DATEDIFF(SECOND, @Date1, @Date2) ) DECLARE @DiffHours INT = @DiffSeconds / 3600 DECLARE @DiffMinutes INT = (@DiffSeconds - (@DiffHours * 3600)) / 60 DECLARE @RemainderSeconds INT = @DiffSeconds % 60 DECLARE @ReturnString VARCHAR(10) SET @ReturnString = RIGHT('00' + CAST(@DiffHours AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@DiffMinutes AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@RemainderSeconds AS VARCHAR(2)), 2) RETURN @ReturnString END </code></pre> <p>I try execute out put like this:</p> <pre><code>SELECT t.vtid, dbo.FormattedTimeDiff(PayDate, DelDate) FROM dbo.Transaction_tbl t where t.Locid = 5 </code></pre> <p>but I am getting output like this:</p> <pre><code>vtid ----------- ---------- 7 00:21:42 7 01:05:30 7 00:37:43 7 NULL 8 00:00:42 8 00:07:25 7 00:25:36. </code></pre> <p>I want to get sum of date difference of vtid 7 and 8</p> <p>Expected output:</p> <pre><code>vtid 7 01:25:45 8 00:07:45 </code></pre> <p>I tried giving group by but showing error, so where I have to made changes in my stored procedure?</p>