------解决方案-------------------- 你这小时跟日期是一个列还是分开的啊?
假设是分开的吧
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 ------解决方案--------------------