小编典典

T-SQL查询组按日期顺序(gaps and islands)

sql

我有一个这样的示例表:

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

像这样的一些样本数据

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)

我需要按日期顺序和vKey / DKey组合对数据进行分组,并像这样显示

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

最好的方法是什么?

提前致谢


阅读 222

收藏
2021-03-08

共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)

2021-03-08