2017-03-20 49 views
0

第三方系统(传感器)在识别出某个地点的移动时将发送信息(传感器ID和日期时间)。SQL中用于DateTime的分类逻辑

SensorID DatetimeInformation 
    1   3/20/2017 07:05 
    1   3/20/2017 07:15 
    1   3/20/2017 07:35 
    1   3/20/2017 07:55 
    2   3/20/2017 07:11 
    2   3/20/2017 07:19 
    2   3/20/2017 07:45 
    2   3/20/2017 07:58 

我想seperately写SQL逻辑每隔1小时后进行分类上述信息

SensorID Date   TimeDuration DateTimeInformationList (store as VarBinary(Max)) 
1   3/20/2017  7AM - 8AM  3/20/2017 07:05, 3/20/2017 07:15 ,3/20/2017 07:35,3/20/2017 07:55 
2   3/20/2017  7AM - 8AM  3/20/2017 07:11, 3/20/2017 07:19 ,3/20/2017 07:45,3/20/2017 07:58 
+0

看看这篇文章:HTTPS:/ /www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ – Horaciux

回答

0
Declare @YourTable table (SensorID int,DatetimeInformation datetime) 
Insert Into @YourTable values 
(1 ,'3/20/2017 07:05'), 
(1 ,'3/20/2017 07:15'), 
(1 ,'3/20/2017 07:35'), 
(1 ,'3/20/2017 07:55'), 
(2 ,'3/20/2017 07:11'), 
(2 ,'3/20/2017 07:19'), 
(2 ,'3/20/2017 07:45'), 
(2 ,'3/20/2017 07:58') 

;with cte as (
     Select SensorID 
       ,MinDT  = Min(DatetimeInformation) 
       ,MaxDT  = Max(DatetimeInformation) 
     From @YourTable 
     Group By SensorID 
       ,Convert(date,DatetimeInformation) 
       ,DatePart(HOUR,DatetimeInformation) 
) 
Select SensorID 
     ,Date = Convert(date,MinDT) 
     ,TimeDuration = Format(MinDT,'htt')+ ' - ' + Format(DateAdd(HOUR,1,minDT),'htt') 
     ,DateTimeInformationList = Stuff((Select ', ' +Format(DatetimeInformation,'M/dd/yyyy h:mm') 
             From @YourTable 
             Where SensorID=A.SensorID 
              and DatetimeInformation between A.MinDT and A.MaxDT 
             Order By DatetimeInformation 
             For XML Path ('') 
             ),1,2,'') 
from cte A 

返回

SensorID Date   TimeDuration DateTimeInformationList 
1   2017-03-20 7AM - 8AM  3/20/2017 7:05, 3/20/2017 7:15, 3/20/2017 7:35, 3/20/2017 7:55 
2   2017-03-20 7AM - 8AM  3/20/2017 7:11, 3/20/2017 7:19, 3/20/2017 7:45, 3/20/2017 7:58 
+0

这很奇妙。是否有可能找到该TimeDuration的所有DatetimeInformationList的平均时间间隔(分钟或秒)? – Marid

+0

SELECT DATEDIFF(分,pDataDate,DatetimeInformation) \t \t \t \t FROM( \t \t \t \t \t \t \t SELECT *, \t \t \t \t \t \t \t LAG(DatetimeInformation)OVER(ORDER BY DatetimeInformation)pDataDate \t \t \t \t \t \t \t从TestSensor 凡SensorID = A.SensorID 和A.MinDT和A.MaxDT之间DatetimeInformation \t \t \t \t \t \t)● \t \t \t \t \t \t WHERE pDataDate IS NOT NULL – Marid