select sum(ft.ettiliq-ft.efinv) as ivavalor, ftstamp
into #calciva
from ft
where (ft.tiposaft='FT' or ft.tiposaft='NC' or ft.tiposaft='FR' or ft.tiposaft='FS')
and ft.fno>0 and ft.anulada=0
group by ftstamp
select *, case when Vendas_ano_anterior=0 then 0 when Vendas_este_ano=0 then 0
else (Vendas_este_ano-Vendas_ano_anterior)/Vendas_ano_anterior end as variacao
from (
select RANK() OVER(ORDER BY sum(case when year(ft.fdata)=year(getdate()) then (ivavalor)
else 0 end) DESC) as posicao,
case when cl.estab>0 then ltrim(rtrim(cl.nome))+' - '+
convert(varchar(10),cl.no)+' - '+
convert(varchar(10),cl.estab)
else cl.nome+ ' - ' +convert(varchar(10),cl.no) end as Nome,
cl.clstamp as stamp,
case when sum(case when year(ft.fdata)=year(getdate()) then (ivavalor)
else 0 end) > 1000000
then round(sum(case when year(ft.fdata)=year(getdate()) then (ivavalor)
else 0 end),0)
else sum(case when year(ft.fdata)=year(getdate()) then (ivavalor)
else 0 end) end as Vendas_este_ano,
isnull((sum(case when year(ft.fdata)=year(getdate()) then (ivavalor)
else 0 end))
/ (select sum((ivavalor)) from ft inner join #calciva on #calciva.ftstamp = ft.ftstamp
where year(ft.fdata)=year(getdate())), 0) *100 as percentagemdototal,
case when sum(case when year(ft.fdata)=year(getdate())-1 and month(ft.fdata)<=month(getdate()) then (ivavalor)
else 0 end) > 1000000
then round(sum(case when year(ft.fdata)=year(getdate())-1
and month(ft.fdata)<=month(getdate()) then (ivavalor) else 0 end),0)
else sum(case when year(ft.fdata)=year(getdate())-1 and month(ft.fdata)<=month(getdate()) then (ivavalor)
else 0 end) end as Vendas_ano_anterior,
isnull(((sum(case when year(ft.fdata)=year(getdate())-1 and
month(ft.fdata)<=month(getdate()) then (ivavalor) else 0 end))
/ (select sum((ivavalor)) from ft inner join #calciva on #calciva.ftstamp = ft.ftstamp
where year(ft.fdata)=year(getdate())-1 and
month(ft.fdata)<=month(getdate()))),0) *100 as percentagemdototaldoanopassado,
(sum(case when year(ft.fdata)=year(getdate()) then (ivavalor) else 0 end) -
sum(case when year(ft.fdata)=year(getdate())-1 and month(ft.fdata)<=month(getdate())
then (ivavalor) else 0 end)) as Variação_Valor
from ft (nolock)
inner join cl (nolock) on cl.no=ft.no and cl.estab=ft.estab
inner join #calciva on #calciva.ftstamp = ft.ftstamp
inner join td on td.ndoc=ft.ndoc and td.[excluianalises]=0
where (ft.tiposaft='FT' or ft.tiposaft='NC' or ft.tiposaft='FR' or ft.tiposaft='FS')
and ft.fno>0 and ft.anulada=0
group by cl.nome,cl.clstamp, cl.estab, cl.no
)t
where t.Vendas_ano_anterior<>0 or t.Vendas_este_ano<>0