取最大8小时平均最大值
表结构:ID,HourID,dataValue
数据: 1, 2013-01-01 01 3.23
1, 2013-01-01 02 5.23
1, 2013-01-01 03 3.23
1, 2013-01-01 04 4.23
1, 2013-01-01 05 8.23
1, 2013-01-01 06 3.23
1, 2013-01-01 09 3.23
1, 2013-01-01 10 3.23
1, 2013-01-01 12 3.23
1, 2013-01-01 23 3.23
2, 2013-01-01 02 5.23
2, 2013-01-01 03 3.23
2, 2013-01-01 04 4.23
2, 2013-01-01 05 8.23
2, 2013-01-01 06 3.23
2, 2013-01-01 09 3.23
2, 2013-01-01 10 3.23
2, 2013-01-01 12 3.23
2, 2013-01-01 23 3.23
要求:按ID取得8小时平均的最大值。
结果:ID,DayID,dataValue
1 2013-01-01 3.23
2 2013-01-01 5.23
注:每日8小时平均值为0点~7点,1点~8点,... 16点~23点,取得这些时间段的平均值,之后按ID,日期取最大值得出要求结果。
[解决办法]
;with cte as(
select a.*,b.number st,b.number+7 et from (select distinct id,left(hourid,10)data from tb)a
,master..spt_values b where type='P' and number<=16
)
,cte1 as
(select a.id,a.data,b.dva from cte a cross apply
(select avg(datavalue)dva from tb where a.id=b.id and right(b.hourid,2)>=a.st and right(b.hourid,2)<=a.et)b
)
select id,data,max(dva)dva from cte1 group by id,data
[解决办法]