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IT.CD_BENEF,0)				   AS CD_BENEF
  FROM dbo.PDV_VD_IT
	   LEFT OUTER JOIN (SELECT dbo.PDV_VD_EST_NF_ENT.CD_EMP
							  ,dbo.PDV_VD_EST_NF_ENT.CD_FILIAL
							  ,dbo.PDV_VD_EST_NF_ENT.CD_NF
							  ,dbo.PDV_VD_EST_NF_ENT.CD_VD
							  ,dbo.EST_NF_ENT_IT.CD_PROD
							  ,dbo.EST_NF_ENT_IT.QT_IT
						  FROM dbo.EST_NF_ENT_IT
								    INNER JOIN dbo.PDV_VD_EST_NF_ENT ON dbo.EST_NF_ENT_IT.CD_EMP = dbo.PDV_VD_EST_NF_ENT.CD_EMP
						  											AND dbo.EST_NF_ENT_IT.CD_FILIAL = dbo.PDV_VD_EST_NF_ENT.CD_FILIAL
						  											AND dbo.EST_NF_ENT_IT.CD_NF = dbo.PDV_VD_EST_NF_ENT.CD_NF
						 WHERE (NOT EXISTS (
											SELECT CD_EMP
											  FROM dbo.EST_NF_ENT
											 WHERE (CD_EMP = dbo.EST_NF_ENT_IT.CD_EMP)
											   AND (CD_FILIAL = dbo.EST_NF_ENT_IT.CD_FILIAL)
											   AND (CD_NF = dbo.EST_NF_ENT_IT.CD_NF)
											   AND (STS_NF = 1))
								)
								) AS NF_ENTRADA ON dbo.PDV_VD_IT.CD_EMP = NF_ENTRADA.CD_EMP
											   AND dbo.PDV_VD_IT.CD_FILIAL = NF_ENTRADA.CD_FILIAL
											   AND dbo.PDV_VD_IT.CD_VD = NF_ENTRADA.CD_VD
											   AND dbo.PDV_VD_IT.CD_PROD = NF_ENTRADA.CD_PROD
 GROUP BY dbo.PDV_VD_IT.CD_EMP
	     ,dbo.PDV_VD_IT.CD_FILIAL
	     ,dbo.PDV_VD_IT.CD_VD
	     ,dbo.PDV_VD_IT.CD_IT
	     ,dbo.PDV_VD_IT.CD_PROD
	     ,dbo.PDV_VD_IT.QT_IT
	     ,dbo.PDV_VD_IT.QT_EST_ANT
	     ,dbo.PDV_VD_IT.VLR_IT
	     ,dbo.PDV_VD_IT.TX_DESC
	     ,dbo.PDV_VD_IT.ST_IT
	     ,dbo.PDV_VD_IT.CD_VEND
	     ,dbo.PDV_VD_IT.VLR_PMZ
	     ,dbo.PDV_VD_IT.VLR_CUSTO
	     ,dbo.PDV_VD_IT.PERC_APLIC
	     ,dbo.PDV_VD_IT.COEF_PMZ
	     ,dbo.PDV_VD_IT.VLR_DESC_TOT_RAT
	     ,dbo.PDV_VD_IT.TOT_IT
	     ,dbo.PDV_VD_IT.CD_TRIB_FC
	     ,dbo.PDV_VD_IT.TX_ICMS_IT
	     ,dbo.PDV_VD_IT.TX_RED_IT
	     ,dbo.PDV_VD_IT.DT_CONSD
	     ,dbo.PDV_VD_IT.PERC_COMI
	     ,dbo.PDV_VD_IT.PERC_COMI_CTR
	     ,dbo.PDV_VD_IT.PERC_DESC_CTR
		 ,PDV_VD_IT.MOTIVO_DESONERADO_ICMS
		 ,PDV_VD_IT.CD_BENEF