DECLARE @temp table(CODE int,TOTALAMOUNT int)
declare @code int
declare row_cur scroll cursor for
select distinct code from dbo.His_Day_1 order by code
open row_cur
fetch first from row_cur into @code
while @@fetch_status=0
begin
insert into @temp(code,totalamount)
select code,avg(totalamount) from
(select top 5 code,totalamount from dbo.His_Day_1 where code=@code order by time desc) a group by code
fetch next from row_cur into @code
end
close row_cur
deallocate row_cur
select * from @temp order by code