1

这是我当前的数据集:

Id                                      Province    Time
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-04 16:38:06.000
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-05 07:58:08.000
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-05 10:43:07.000
18D066A7-4FFB-462A-A203-DF468F814A43    QC          2013-09-05 10:44:07.000
18D066A7-4FFB-462A-A203-DF468F814A43    QC          2013-09-05 10:45:07.000
18D066A7-4FFB-462A-A203-DF468F814A43    QC          2013-09-05 11:12:07.000
18D066A7-4FFB-462A-A203-DF468F814A43    QC          2013-09-05 11:58:08.000
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-05 12:00:08.000

以上数据存储在 CTE 中,以下是查询:

;With CTE
AS
(
Select S.Id, S.Province, MIN(S.LocalTimeStamp) As MinTime From Table S 
    Where [Description] = 'Test Desc'
    Group By Id, Province, Zone
)   

Select * From CTE
    Order By CTE.MinTime

预期结果:

Id                                      Province    Time
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-04 16:38:06.000
18D066A7-4FFB-462A-A203-DF468F814A43    QC          2013-09-05 10:44:07.000
18D066A7-4FFB-462A-A203-DF468F814A43    ON          2013-09-05 12:00:08.000

场景是:一辆车从 ON 开始到 QC 并返回 ON。

我想要在 ON 省内的开始和返回单独的行。当TIME落在不同的日期时,它可以正常工作,因为我可以按 Date 的TIME部分分组。但问题是三个人都在同一天。

可以做到吗?

4

1 回答 1

0

如果您比较初始日期和后续日期之间的时差会怎样?像这样的东西:

-- First, get the initial date:
;WITH CTE1
AS
(Select Id, MIN(S.LocalTimeStamp) As MinTime From Table S 
    Where [Description] = 'Test Desc' AND Province = 'ON'
    Group By Id 

, CTE2
AS
(
Select S.Id, S.Province, MIN(DATEDIFF(ms, CTE1.MinTime, S.LocalTimeStamp)) As MinTime, S.LocalTimeStamp
From Table S
    INNER JOIN CTE1
        ON Table.ID = CTE1.ID 
Where [Description] = 'Test Desc'
Group By Id, Province, Zone
)   

Select * From CTE2
    Order By CTE.MinTime
于 2013-10-25T23:59:13.367 回答