select ft.ftstamp as stamp,ft.nmdoc + ´ nº ´ +
ltrim(rtrim(convert(char(10),ft.fno))) as documento,
ft.fdata as data,
case when ft.estab>0 then ltrim(rtrim(ft.nome))+´ - ´+
convert(varchar(10),ft.no)+´ - ´+
convert(varchar(10),ft.estab)else ft.nome+ ´ - ´ +
convert(varchar(10),ft.no) end as nome,
isnull(sum(case when td.tiposaft=´NC´ then -fi.qtt when td.tiposaft<>´NC´
then fi.qtt end),0) as quantidade,
sum(fi.etiliquido) as valor
from ft(nolock)
inner join td(nolock) on td.ndoc=ft.ndoc and td.[excluianalises]=0
inner join fi(nolock) on fi.ftstamp=ft.ftstamp
where fi.familia=(case when ´#STAMP2#´=´Sem Família Definida´ then ´´ else ´#STAMP2#´ end)
and ft.fdata>=´#1#´ and ft.fdata<=´#2#´ and ft.anulada=0 and ft.fno>0
and (td.tiposaft=´FT´ or td.tiposaft=´FS´ or td.tiposaft=´FR´
or (td.tiposaft=´NC´ and td.regrd=0) or td.tiposaft=´ND´)
and fi.qtt<>0group by ft.ftstamp, ft.nmdoc, ft.fno, ft.no, ft.estab,
ft.fdata, ft.nome
order by ft.fdata, ft.nmdoc, ft.fno, ft.no, ft.estab