T-SQL query group in date order (gaps and islands)

最后都变了- 提交于 2019-12-24 00:42:20

问题


I have a sample table like this:

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

with some sample data like so

INSERT INTO #Aggregate
    (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


回答1:


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



来源:https://stackoverflow.com/questions/40307623/t-sql-query-group-in-date-order-gaps-and-islands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!