Insert Into Heartbeat 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 HeartBeat
Where SensorID=A.SensorID
and DatetimeInformation between A.MinDT and A.MaxDT
Order By DatetimeInformation
For XML Path ('')
),1,2,'')
from cte A
返回在SQL Server計算最小值,最大值和平均值的時間字符串列表
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
我能得到幫助,以組每小時Datetimeinformation這是上面的查詢。 我需要獲得該TimeTime的所有DatetimeInformationList(上午7點至上午8點)的平均時間間隔(分鐘或秒)
當我嘗試插入另一2行與(1, '3/20/2017年08:05'),(1, ''3/20/2017 08:15'),那麼Sensor ID 1應該有2行,一個是7AM到8AM,另一個是上午8AM到9AM,平均值應該是分別從上午7AM到上午8AM以及上午8AM到上午9AM。但是下面的答案是選擇SensorID 1的所有日期並計算平均值。它應該根據時間間隔進行計算。 – Marid