Mountaineer Mountaineer - 1 month ago 6
SQL Question

TSQL 2008r2 Query Group in Date Order (Gaps and Islands)

SQL Server 2008r2

Hi

I have a sample table like so

CREATE TABLE #Aggrgate(
vKey INT
,dKey INT
,StartTrip DATETIME
,EndTrip DATETIME
,Distance INT
)


with some sample data like so

INSERT INTO #Aggrgate
(vKey, dKey, StartTrip, EndTrip, Distance )
VALUES
(4940, 0, '2016-09-14 09:05:47.000', '2016-09-14 10:07:45.000', 25)
,(4940, 0, '2016-09-15 14:09:40.000', '2016-09-15 14:11:33.000', 35)
,(4940, 1202, '2016-09-16 17:07:04.000', '2016-09-16 18:07:04.000', 61)
,(4940, 0, '2016-09-26 16:43:03.000', '2016-09-26 16:44:52.000', 0)
,(4940, 0, '2016-09-28 11:13:41.000', '2016-09-28 11:14:33.000', 5)
,(4940, 1202, '2016-10-01 13:41:03.000', '2016-10-01 14:02:39.000', 500)
,(4940, 1202, '2016-10-01 21:52:14.000', '2016-10-01 21:54:28.000', 5)
,(4940, 0, '2016-10-01 10:27:44.000', '2016-10-01 10:36:24.000', 75)


I need to group the data in date order and in vKey/DKey combinations and present like so

vKey dKey StartTrip EndTrip Distance
4940 0 14/09/2016 09:05:47 15/09/2016 14:11:33 60
4940 1202 16/09/2016 17:07:04 16/09/2016 18:07:04 61
4940 0 26/09/2016 16:43:03 28/09/2016 11:14:33 5
4940 1202 01/10/2016 13:41:03 01/10/2016 21:54:28 505
4940 0 01/10/2016 10:27:44 01/10/2016 10:36:24 75


What is the best approach to take?

Thanks in advance

Answer
Select vKey
      ,dKey
      ,StartTrip = min(StartTrip) 
      ,EndTrip   = max(EndTrip) 
      ,Distance  = sum(Distance)
From (
Select *
      ,Island = Row_Number() over (Partition By vKey Order by Month(StartTrip)) - Row_Number() over (Partition By vKey,dKey Order by StartTrip)
  from #Aggrgate
) A
Group By Island,vKey,dKey
Order By min(StartTrip) 

Returns

enter image description here