select
  r.filial,
  r.ano,
  r.mes,
  r.dia,
  sum(nfe) qtd_nfe,
  sum(total_nfe) valor_nfe,
  sum(nfce) qtd_nfce,
  sum(total_nfce) valor_nfce,
  sum(devemit) qtd_dev_emit,
  sum(total_devemit) valor_dev_emit,
  sum(devrec) qtd_dev_rec,
  sum(total_devrec) valor_dev_rec,
  sum(total_vendas) liquido_vendas
from (
  select
    iif(n.operacao in (1003,1125,1145,1161) and n.filial = 1,100, iif(n.operacao in (1117,1162) and n.filial = 1,200,n.filial)) filial,
    extract(year from n.emissao) ano,
    extract(month from n.emissao) mes,
    extract(day from n.emissao) dia,
    sum(iif(n.modelo = 55, iif(n.opfinanceiro = '+', 1, 0), 0)) NFE,
    sum(iif(n.modelo = 55, iif(n.opfinanceiro = '+', n.total, 0), 0)) total_NFE,
    sum(iif(n.modelo = 65, 1, 0)) NFCE,
    sum(iif(n.modelo = 65, n.total, 0)) total_NFCE,
    sum(iif(n.modelo = 55, iif(n.opfinanceiro = '-', -1, 0), 0)) devemit,
    sum(iif(n.modelo = 55, iif(n.opfinanceiro = '-', -n.total, 0), 0)) total_devemit,
    sum(0) devrec,
    sum(0) total_devrec,
    sum(iif(n.opfinanceiro='+', n.total, -n.total)) total_vendas
  from
    notas_emitidas n
  where
    n.emissao >= :Data_Inicial and n.emissao < :Data_Final + 1
    and n.cancelada = 'N'
    and n.opfinanceiro <> '='
    and n.nf > 0

  group by
    1, 2, 3, 4

  union all

  select
    n.filial,
    extract(year from n.data) ano,
    extract(month from n.data) mes,
    extract(day from n.data) dia,
    0,
    0,
    0,
    0,
    0,
    0,
    sum(-1),
    sum(-n.total),
    sum(-n.total)
  from
    notas_recebidas n
  where
    n.data >= :Data_Inicial and n.data < :Data_Final + 1
    and n.tipo = 'F'
    and n.opfinanceiro = '-'
    and n.nf_numero > 0
    and n.cancelada <> 'S'

  group by
    1, 2, 3, 4, 5

  )r
where
  filial = :filial or :filial = 0
group by
  1, 2, 3, 4
order by
  1, 2, 3, 4
