SELECT DATEDIFF(ss,TranIn,TranOut) AS SECONDS,COUNT(*) AS CNTFROM #tmpGROUP BY DATEDIFF(ss,TranIn,Tranout) /* resultSECONDS CNT0 11 14 15 19 112 115 1*/
;with CTE AS( -- get the elapsed time in seconds for each transaction, with a count by # of secondsselect sec = DateDiff(second, TranIn, TranOut), qty = count(*) from #tmp group by DateDiff(second, TranIn, TranOut)), Tally AS -- if you already have a tally table, you can omit it here and use it below( -- build a tally table of numbers between 1 and 10select Number from master.dbo.spt_values where [Type] = 'P' and number between 1 and 10)-- now bring them all togetherselect [Second] = Tally.Number, [Quantity of Transactions] = case when CTE.sec is null then 0 else CTE.qty end, [Description] = convert(varchar(2), Tally.Number) + ' second' + case when Tally.Number = 1 then '' else 's' end + ' -- ' + convert(varchar(10), case when CTE.sec is null then 0 else CTE.qty end) + ' transactions' from Tally LEFT OUTER JOIN CTE ON Tally.Number = CTE.sec where Tally.Number between 1 and 10 -- this line is only needed if using your own tally table.