簡體   English   中英

按日期順序(間隙和島)的T-SQL查詢組

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

我有一個這樣的樣本表:

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

最好的方法是什么?

提前致謝

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) 

返回

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM