IF EXISTS (SELECT * FROM sysobjects O, sysusers U
          WHERE
            o.name = 'VENDA_VIEW'  and
            type = 'V'                  and
            u.uid = o.uid               and
            u.name = USER)
   DROP VIEW VENDA_VIEW;
GO

CREATE VIEW VENDA_VIEW
(CDFILIAL,NMFILIAL,CDCAIXA,NMCAIXA,NRSEQVENDA,CDCLIENTE,CDLOJA,NMLOJA,DTVENDA,DTENTRVENDA,IDSITUVENDA,
 QTTOTALPROD,VRVENDA,VRDESCONTO,VRIMPOSTO) AS
  SELECT
    VE.CDFILIAL,FI.NMFILIAL,VE.CDCAIXA,CA.NMCAIXA,VE.NRSEQVENDA,VE.CDCLIENTE,
    VE.CDLOJA,LO.NMLOJA,VE.DTVENDA, VE.DTENTRVENDA,VE.IDSITUVENDA,
    SUM(IT.QTPRODVEND) AS QTTOTALPROD,
    SUM((IT.QTPRODVEND * (ISNULL(IT.VRUNITVEND,0) + ISNULL(IT.VRUNITVENDCL,0)))) AS VRVENDA,
    SUM(IT.VRDESITVEND) AS VRDESCONTO,
    SUM((IM.VRPEALPRODIT/100)*((IT.QTPRODVEND * (ISNULL(IT.VRUNITVEND,0) + ISNULL(IT.VRUNITVENDCL,0))) - ISNULL(IT.VRDESITVEND,0))) AS VRIMPOSTO
  FROM
    FILIAL FI, VENDA VE, CAIXA CA, LOJA LO, ITEMVENDA IT LEFT JOIN
       (SELECT SUM(IM.VRPEALPRODIT) AS VRPEALPRODIT, IM.CDFILIAL, IM.CDCAIXA, IM.NRSEQVENDA, IM.NRSEQUITVEND
        FROM ITVENDAIMPOS IM, ITEMVENDA IT
        WHERE (IM.CDFILIAL     = IT.CDFILIAL    ) AND
           (IM.CDCAIXA      = IT.CDCAIXA     ) AND
           (IM.NRSEQVENDA   = IT.NRSEQVENDA  ) AND
           (IM.NRSEQUITVEND = IT.NRSEQUITVEND)
        GROUP BY IM.CDFILIAL, IM.CDCAIXA, IM.NRSEQVENDA,IM.NRSEQUITVEND ) IM ON(IM.CDFILIAL     = IT.CDFILIAL    ) AND
                                                                               (IM.CDCAIXA      = IT.CDCAIXA     ) AND
                                                                               (IM.NRSEQVENDA   = IT.NRSEQVENDA  ) AND
                                                                               (IM.NRSEQUITVEND = IT.NRSEQUITVEND)
  WHERE
    FI.CDFILIAL   = VE.CDFILIAL   AND
    VE.CDFILIAL   = IT.CDFILIAL   AND
    VE.CDCAIXA    = IT.CDCAIXA    AND
    VE.NRSEQVENDA = IT.NRSEQVENDA AND
    VE.CDFILIAL   = CA.CDFILIAL   AND
    VE.CDCAIXA    = CA.CDCAIXA    AND
    VE.CDFILIAL   = LO.CDFILIAL   AND
    VE.CDLOJA     = LO.CDLOJA
  GROUP BY
    VE.CDFILIAL,FI.NMFILIAL,VE.CDCAIXA,CA.NMCAIXA,VE.NRSEQVENDA,VE.CDCLIENTE,
    VE.CDLOJA,LO.NMLOJA,VE.DTVENDA, VE.DTENTRVENDA, VE.IDSITUVENDA
GO