select
 r.filial,
 r.vendedor,
 sum(r.total_vendas) total_vendas,
 avg(r.media_itens_por_nf) media_itens,
 avg(r.ticket_medio) ticket_medio
from(
select
  r.*,
  cast((r.vendas_quant + 0.00) / (datediff(day from :Data_Inicial to :Data_Final) + 1) as numeric(13,2)) v_quant_media_diaria,
  cast(iif(r.vendas_quant > 0, r.itens_quant * 1.00 / r.vendas_quant * 1.00, 0) as numeric(13,2)) media_itens_por_nf,
  r.total_vendas / (datediff(day from :Data_Inicial to :Data_Final) + 1) v_media_diaria,
  cast(iif(r.vendas_quant > 0, r.total_vendas / r.vendas_quant, 0) as numeric(13,2)) ticket_medio
from

(
  select
    filial,
    vendedor,
    nome,
    sum(vendas_quant_total) vendas_quant_total,
    sum(devolucoes) devolucoes,
    sum(vendas_quant_total - devolucoes) vendas_quant,
    sum(itens_quant) itens_quant,
    sum(total_vendas) total_vendas
  from

  (
    select
      notas.filial filial,
      notas.vendedor,
      o.nome,
      iif(notas.opfinanceiro = '+', 1, 0) vendas_quant_total,
      iif(notas.opfinanceiro = '-', 1, 0) devolucoes,
      iif(notas.opfinanceiro = '+', notas.itens, -notas.itens) itens_quant,
      iif(notas.opfinanceiro = '+', notas.valor, -notas.valor) total_vendas
    from

    (
      select
        ne.nota,
        ne.filial filial_original,
        ne.vendedor,
        cast(ne.total as numeric(13,2)) valor,
        ne.opfinanceiro,
        ne.operacao,
        iif(ne.filial = 1 and ne.operacao in (1003, 1125, 1145, 1161), 100, iif(ne.filial = 1 and ne.operacao in (1117, 1162), 200, ne.filial)) filial,
        count(distinct ie.item) itens
      from
        notas_emitidas ne
        inner join itens_emitidos ie on ie.nota = ne.nota and ie.filial = ne.filial
      where
        ne.cancelada = 'N'
        and ne.data >= :Data_Inicial and ne.data < :Data_Final + 1
        and ne.opfinanceiro in ('+', '-')
        and (ne.vendedor = :Vendedor or :Vendedor = 0)
      group by
        1, 2, 3, 4, 5, 6
  ) notas

    inner join operadores o on o.operador = notas.vendedor
  where
    (notas.filial = :Filial or :Filial = 0)
) totais

group by
  1, 2, 3
) r
)r
group by
  1, 2
