这是我当前的数据集:
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 落在不同日期时它可以正常工作,因为我可以按 TIME 的日期部分进行分组。但问题是当这三个人都在同一天。
可以吗?
答案 0 :(得分: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