select RANK() OVER(ORDER BY Valor_em_stock DESC) as posicao, ref as ref, stamp as stamp,
t.Designação as design,
t.[Quantidade em stock] as quantidadestock,
t.[Preço de custo ponderado] as precocustoponderado,
case when t.Valor_em_stock > 1000000 then round(t.Valor_em_stock,0)
else t.Valor_em_stock end valorstock,
t.Percentagem_do_total * 100 as percentagemdototal,
sum(Percentagem_do_total) OVER (ORDER BY (Valor_em_stock)
ROWS between UNBOUNDED PRECEDING and CURRENT ROW) *100 as percentagemacumuladadototal
from (select ref as ref, ststamp as stamp, design as 'Designação',
case when stock < 0 then 0 else stock end as 'Quantidade em stock',
epcpond as 'Preço de custo ponderado', stock*epcpond as Valor_em_stock,
case when sum(stock* epcpond) over() = 0 then 0
else stock*epcpond/sum(stock*epcpond) over() end as Percentagem_do_total
from st where st.stns = 0)t Order By Valor_em_stock desc