 IF  EXISTS (SELECT * FROM SYS.VIEWS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[V_PDV_VD_CARTAO]'))
	DROP VIEW [DBO].[V_PDV_VD_CARTAO]
GO

CREATE VIEW [dbo].[V_PDV_VD_CARTAO]  
AS  
SELECT       
 dbo.PDV_VD.CD_EMP,   
 dbo.PDV_VD.CD_FILIAL,   
 dbo.PDV_VD.CD_VD,   
 dbo.PDV_VD.DT_VD,   
 dbo.PDV_VD_TEF.VL_CARTAO - ISNULL(T2.VLR_TOT_CUPOM,0) AS VLR_CARTAO,   
    ISNULL(dbo.RC_ADM_CARTAO.TP_ADM, 0) AS TP_ADM,   
 dbo.PDV_VD.ST_VD,  
 dbo.PDV_VD.CD_CX  
FROM           
 dbo.PDV_VD INNER JOIN PDV_VD_TEF ON  
 PDV_VD.CD_EMP = PDV_VD_TEF.CD_EMP AND  
 PDV_VD.CD_FILIAL = PDV_VD_TEF.CD_FILIAL AND  
 PDV_VD.CD_VD = PDV_VD_TEF.CD_VD   
 LEFT OUTER JOIN dbo.RC_ADM_CARTAO ON   
 dbo.PDV_VD_TEF.CD_EMP = dbo.RC_ADM_CARTAO.CD_EMP AND   
    dbo.PDV_VD_TEF.CD_ADM_CARTAO = dbo.RC_ADM_CARTAO.CD_ADM_CARTAO  

LEFT JOIN
  (SELECT PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_EMP,
          PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_FILIAL,
          PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_CX,
          PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.NR_ECF,
          PDV_CUPOM_NAO_FISCAL.DT_CUPOM,
          PDV_CUPOM_NAO_FISCAL.VLR_TOT_CUPOM
   FROM PDV_CUPOM_NAO_FISCAL_SUPER_TROCO
   INNER JOIN PDV_CUPOM_NAO_FISCAL ON PDV_CUPOM_NAO_FISCAL.CD_EMP = PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_EMP
   AND PDV_CUPOM_NAO_FISCAL.CD_FILIAL = PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_FILIAL
   AND PDV_CUPOM_NAO_FISCAL.CD_CTR = PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_CTR
   AND PDV_CUPOM_NAO_FISCAL.CD_CX = PDV_CUPOM_NAO_FISCAL_SUPER_TROCO.CD_CX
   WHERE PDV_CUPOM_NAO_FISCAL.ST_CUPOM = 0) T2 ON PDV_VD.CD_EMP = T2.CD_EMP
        AND PDV_VD.CD_FILIAL = T2.CD_FILIAL 
     AND PDV_VD.CD_CX = T2.CD_CX 
     AND PDV_VD.NR_ECF = T2.NR_ECF 
     AND PDV_VD.DT_VD = T2.DT_CUPOM 
  
WHERE       
 dbo.PDV_VD_TEF.VL_CARTAO > 0   
 AND dbo.PDV_VD_TEF.CD_ADM_CARTAO > 0   
 AND NOT EXISTS (SELECT       
       CD_VD  
      FROM            
       PDV_VD_CANCEL_TEF  
      WHERE        
      PDV_VD.CD_EMP = PDV_VD_CANCEL_TEF.CD_EMP AND   
      PDV_VD.CD_FILIAL = PDV_VD_CANCEL_TEF.CD_FILIAL AND   
                        PDV_VD.CD_VD = PDV_VD_CANCEL_TEF.CD_VD)   
      AND dbo.PDV_VD.ST_VD = 0

 
   