	IF  EXISTS (SELECT * FROM SYS.VIEWS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[V_EST_NF_ENT_CAB_DAR]'))

	DROP VIEW [DBO].[V_EST_NF_ENT_CAB_DAR]    
	GO
  
	CREATE VIEW [DBO].[V_EST_NF_ENT_CAB_DAR]   -- SELECT * FROM V_EST_NF_ENT_CAB_DAR where cd_emp = 1 and cd_filial = 999 AND cd_NF = 5323
	WITH ENCRYPTION AS  
	-- VERSAO 3438   SELECT  * FROM EST_NF_ENT_DAR_IT WHERE CD_FILIAL =999 AND cd_NF = 5323

SELECT 
	CD_EMP,
	CD_FILIAL,
	CD_NF,
	SUM(VLR_CAB_BASE_ICMS_DARE) VLR_CAB_BASE_ICMS_DARE,
	SUM(VLR_CAB_ICMS_DARE) VLR_CAB_ICMS_DARE,
	SUM(VLR_ICMS_SUBS_DARE) AS VLR_ICMS_SUBS_DARE,
	SUM(VLR_BASE_SUBS_DARE) AS VLR_BASE_SUBS_DARE,
	SUM(VLR_CUSTO_DARE) AS VLR_CUSTO_DARE,
	SUM(VLR_BASE_ICMS_RETIDO_DARE) AS VLR_BASE_ICMS_RETIDO_DARE
FROM (
	SELECT 

		CD_EMP,
		CD_FILIAL,
		CD_NF,

		CASE WHEN EST_TRIB.ICMS  = 1 THEN
			VLR_BASE_ICMS 
		ELSE
			0
		END AS VLR_CAB_BASE_ICMS_DARE  ,
	
		CASE WHEN  EST_TRIB.ICMS  = 1 THEN
			VLR_ICMS 	
		ELSE
		   0
		END AS VLR_CAB_ICMS_DARE,
		
		VLR_ICMS_SUBS AS VLR_ICMS_SUBS_DARE,
		VLR_BASE_SUBS AS  VLR_BASE_SUBS_DARE,
		VLR_CUSTO AS VLR_CUSTO_DARE,
		VLR_BASE_ICMS_RETIDO AS VLR_BASE_ICMS_RETIDO_DARE,
		VLR_ICMS_RETIDO AS VLR_ICMS_RETIDO

	  FROM  EST_NF_ENT_DAR_IT INNER JOIN EST_TRIB ON
		  EST_NF_ENT_DAR_IT.CD_TRIB = EST_TRIB.CD_TRIB

	  --WHERE CD_FILIAL =999 AND cd_NF = 5323

	  ) TEMP
			
			GROUP BY 
				CD_EMP,
				CD_FILIAL,
				CD_NF

