這將提供期望的結果,而無需使用CTE(公用表表達式),其可以是更容易理解,並且可以具有更好的性能。
定義樣本的測試數據:
Declare @test Table
(
IDate Datetime
,ID Int
)
Insert Into @test(IDate,ID) Values
('2015-06-23 00:11:22.387',1000)
,('2015-06-23 00:15:52.192',1000)
,('2015-06-23 00:19:29.344',1000)
,('2015-06-23 00:39:20.660',1000)
,('2015-06-23 01:21:22.387',1000)
,('2015-06-23 01:25:52.192',1000)
,('2015-06-23 01:32:29.344',1000)
,('2015-06-23 01:39:20.660',1000)
,('2015-06-23 23:21:22.387',1000)
,('2015-06-23 23:25:52.192',1000)
,('2015-06-23 23:32:29.344',1000)
,('2015-06-23 23:39:20.660',1000)
,('2015-06-24 00:11:22.387',1000)
,('2015-06-24 00:15:52.192',1000)
,('2015-06-24 00:19:29.344',1000)
,('2015-06-24 00:39:20.660',1000)
查詢:
select *
from
(
select Convert(varchar, DayPeriod, 101) as DayPeriod,
HourIncrement,
count(*) as RecordForHour,
max(rownum) as CumulativeRecords,
min(ID) as ID
from
(
select *,
Row_Number() over (order by IDate asc) as rownum,
DATEADD(dd, 0, DATEDIFF(dd, 0, IDate)) as DayPeriod,
case when DATEPART(mi, IDate) between 0 and 30
then dateHour + ':00 - ' + dateHour + ':30'
else dateHour + ':30 - ' + dateNextHour + ':00'
end as HourIncrement
from
(
select *,
right('00' + Convert(varchar(4), DATEPART(hh, IDate)), 2) as dateHour,
right('00' + Convert(varchar(4), DATEPART(hh, DateAdd(hh, 1, IDate))), 2) as dateNextHour
from @test
) t1
) t2
group by DayPeriod, HourIncrement
) t3
order by CumulativeRecords asc
結果
什麼是與你有困難的部分? –
所以你每天會有48組?假設每個增量都發生了什麼? –
或者您是否需要全部48個,並且稀疏條目指示RecordsForHour = 0(並且不會RecordsForInterval是更好的名稱....) – Stan