IF  EXISTS (SELECT * FROM SYS.VIEWS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[V_NETPOINTS_VD_IT]'))
	BEGIN
		DROP VIEW [DBO].[V_NETPOINTS_VD_IT]
	END
GO
--SELECT TOP  0 * FROM [DBO].[V_NETPOINTS_VD_IT]
CREATE VIEW [DBO].[V_NETPOINTS_VD_IT]
AS
  SELECT
    --TOP 100
    VD.CD_EMP
    ,VD.CD_FILIAL
    ,VD.CD_VD
    ,VD.CD_CX
    ,VD.DT_VD
    ,VD.HR_VD
    ,VD.NR_ECF
    ,VD.NR_ORC
    ,VD.VLR_LIQ_VD
    ,CLI.CGC_CPF
    ,EMP.CGC_EMP
    ,FILIAL.CGC              AS CGC_FILIAL
    ,VD.VLR_DINH
    ,VD.VLR_CHQS
    ,VD.VLR_CARTAO
    ,VD.VLR_TICKETS
    ,VD.VLR_DUP
    ,VD.VLR_CONV
    ,VD.VLR_NCC
    ,VD.VLR_CONV_PBM
    ,PONTOS.ENVIO_FIDEL
    ,IT.CD_IT
    ,PROD.CD_PROD
    ,(SELECT TOP 1
        CD_BARRA
      FROM   EST_PROD_CD_BARRA B
      WHERE  B.CD_EMP = PROD.CD_EMP
             AND B.CD_PROD = PROD.CD_PROD
             AND NAO_EXPORTAR = 0
             AND EAN_CAIXA_FECHADA = 0
      ORDER  BY
       DT_CAD DESC)          AS CD_BARRA
    ,PROD.DS_PROD
    ,IT.QT_IT
    ,IT.TOT_IT / IT.QT_IT    AS VLR_IT
    ,PONTOS.QTDE_PONTO_FIDEL AS QT_PONTOS
    ,IT.QT_EST_ANT
    ,PROD.NM_FABRIC
    ,CASE PROD.CD_ARV_MERC_DEPTO
       WHEN 0 THEN ''
       ELSE PROD.DS_ARV_MERC_DEPTO
     END                     AS DS_ARV_MERC_DEPTO
    ,CASE PROD.CD_ARV_MERC_LINHA
       WHEN 0 THEN ''
       ELSE PROD.DS_ARV_MERC_LINHA
     END                     AS DS_ARV_MERC_LINHA
    ,CASE PROD.CD_ARV_MERC_CATEG
       WHEN 0 THEN ''
       ELSE PROD.DS_ARV_MERC_CATEG
     END                     AS DS_ARV_MERC_CATEG
    ,CASE PROD.CD_ARV_MERC_FAMILIA
       WHEN 0 THEN ''
       ELSE PROD.DS_ARV_MERC_FAMILIA
     END                     AS DS_ARV_MERC_FAMILIA
    ,CASE PROD.CD_MC
       WHEN 0 THEN ''
       ELSE PROD.DS_MC
     END                     AS DS_MC
  FROM   PDV_VD VD
         INNER JOIN RC_CLI CLI
                 ON VD.CD_EMP = CLI.CD_EMP
                    AND VD.CD_CLI = CLI.CD_CLI
         INNER JOIN PRC_EMP EMP
                 ON VD.CD_EMP = EMP.CD_EMP
         INNER JOIN PRC_FILIAL FILIAL
                 ON VD.CD_EMP = FILIAL.CD_EMP
                    AND VD.CD_FILIAL = FILIAL.CD_FILIAL
         INNER JOIN PDV_VD_IT IT
                 ON VD.CD_EMP = IT.CD_EMP
                    AND VD.CD_FILIAL = IT.CD_FILIAL
                    AND VD.CD_VD = IT.CD_VD
         INNER JOIN PDV_VD_IT_FIDELI_CARTAO PONTOS
                 ON IT.CD_EMP = PONTOS.CD_EMP
                    AND IT.CD_FILIAL = PONTOS.CD_FILIAL
                    AND IT.CD_VD = PONTOS.CD_VD
                    AND IT.CD_IT = PONTOS.CD_IT
         INNER JOIN V_EST_PROD_ARV_MERCADOLOGICA PROD
                 ON IT.CD_EMP = PROD.CD_EMP
                    AND IT.CD_PROD = PROD.CD_PROD
  WHERE  VD.CD_EMP = 1
         AND VD.ST_VD = 0
