Я не уверен, что понимаю ваш рейтинг, но я предполагаю, что это скользящее среднее значение 7 (переменный день), ранжированное от лучшего (наибольшее число) до худшего (самое маленькое)
declare @t table (
StockID int, QuoteID int, QuoteDay date, QuoteClose money)
insert into @t
values
(47,230,'20180406',5.12)
, (47,231,'20180407',5.21)
, (47,232,'20180408',5.3)
, (47,233,'20180409',5.21)
, (47,234,'20180410',5.19)
, (47,235,'20180411',5.52)
, (47,236,'20180412',7.16)
, (47,237,'20180413',6.69)
, (47,238,'20180414',6.63)
, (47,239,'20180415',7.02)
, (47,240,'20180416',6.63)
, (47,241,'20180417',6.58)
, (251,100,'20180406',0.1906)
, (251,101,'20180407',0.1969)
, (251,102,'20180408',0.1986)
, (251,103,'20180409',0.2291)
, (251,104,'20180410',0.1963)
, (251,105,'20180411',0.1995)
, (251,106,'20180412',0.2271)
, (251,107,'20180413',0.3722)
, (251,108,'20180414',0.3073)
, (251,109,'20180415',0.3292)
, (251,110,'20180416',0.2905)
, (251,111,'20180417',0.2784)
declare @dayInRank int = 7
;with cte as
(
select rn=row_number()over(partition by StockID order by QuoteDay)
,*
from @t
)
,RollingAvg as
(
select StockID,QuoteDay,RollingAvg=s.RollingSum/@dayInRank
from cte
cross apply (select SUM(QuoteClose) from cte c2 where cte.StockID=c2.StockID and c2.rn between cte.rn-(@dayInRank-1) and cte.rn) s(RollingSum)
where rn>=@dayInRank
)
select *,Rank=Row_Number()over (partition by StockID order by ra.RollingAvg desc)
from RollingAvg ra
order by StockID,QuoteDay