sql - Calculating total time excluding overlapped time & breaks in SQLServer -
sql - Calculating total time excluding overlapped time & breaks in SQLServer -
from list of start time , end times select query, need find out total time excluding overlapping time , breaks.
starttime endtime 2014-10-01 10:30:00.000 2014-10-01 12:00:00.000 -- 90 mins 2014-10-01 10:40:00.000 2014-10-01 12:00:00.000 --0 since overlapped previous 2014-10-01 10:42:00.000 2014-10-01 12:20:00.000 -- 20 mins excluding overlapped time 2014-10-01 10:40:00.000 2014-10-01 13:00:00.000 -- 40 mins 2014-10-01 10:44:00.000 2014-10-01 12:21:00.000 -- 0 previous ones have covered time range 2014-10-13 15:50:00.000 2014-10-13 16:00:00.000 -- 10 mins
so total should 160 mins in case.
i don't want utilize many loops through this. looking simple solution.
declare @table table (starttime datetime2, endtime datetime2) insert @table select '2014-10-01 10:30:00.000', '2014-10-01 12:00:00.000' insert @table select '2014-10-01 10:40:00.000', '2014-10-01 12:00:00.000' insert @table select '2014-10-01 10:42:00.000', '2014-10-01 12:20:00.000' insert @table select '2014-10-01 10:40:00.000', '2014-10-01 13:00:00.000' insert @table select '2014-10-01 10:44:00.000', '2014-10-01 12:21:00.000' insert @table select '2014-10-13 15:50:00.000', '2014-10-13 16:00:00.000' ;with addnr ( -- add together row numbers select starttime, endtime, row_number() on (order starttime, endtime) rowid @table t ), createnewtable ( -- recreate table according overlap time select starttime, endtime, rowid addnr rowid = 1 union select case when a.starttime <= an.starttime , an.starttime <= a.endtime a.starttime else an.starttime end starttime, case when a.starttime <= an.endtime , an.endtime <= a.endtime a.endtime else an.endtime end endtime, an.rowid addnr inner bring together createnewtable on a.rowid + 1 = an.rowid ), getminutes ( -- difference in minutes select datediff(minute,starttime,max(endtime)) diffminutes createnewtable grouping starttime ) select sum(diffminutes) result getminutes
and result 160
sql sql-server
Comments
Post a Comment