日期:2014-05-17  浏览次数:20445 次

取最大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,日期取最大值得出要求结果。
SQl语句 求平均 求最大值

------解决方案--------------------
你这小时跟日期是一个列还是分开的啊?
假设是分开的吧
select id,data,timePoint,max(va)va from
(select id,data,hour%8 as timePoint,avg(value)va 
from tb group by id,data,hour%8)a
------解决方案--------------------
declare @tb table(shour int,ehour int)
declare @t int
set @t=0
while(@t<17)
begin
insert into @tb select @t,@t+7
set @t=@t+1
end
select id,dayid,datavalue=(select max(dv) from (select sum(datavalue)/8 dv from tb c join @tb b on c.hourid between b.shour and ehour  where a.id=c.id and a.dayid=c.dayid group by shour,ehour)t)
from tb a group by id,dayid


------解决方案--------------------
;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
------解决方案--------------------
引用: