CREATE TABLE #RSDANFE (CD_CTR INT, 
				    CD_PROD INT, 
				    PERC_DIFERIMENTO MONEY, 
				    VLR_ICMS_DIFERIMENTO MONEY,  
				    VLR_ICMS_OP MONEY)
CREATE TABLE #RSNFENTRADA (CD_CTR INT, 
					  CD_EMP INT, 
					  CD_FILIAL INT, 
					  CD_NF INT, 
					  CD_PROD INT)

INSERT INTO #RSDANFE
SELECT
	I.CD_CTR,
	I.CD_PROD,
	AVG(I.PERC_DIFERIMENTO) AS PERC_DIFERIMENTO, 
	AVG(I.VLR_ICMS_DIFERIMENTO) AS VLR_ICMS_DIFERIMENTO,
	AVG(I.VLR_ICMS_OP) AS VLR_ICMS_OP
FROM
    EST_NF_ENT_DANFE_PROVISORIO INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS I ON
    EST_NF_ENT_DANFE_PROVISORIO.CD_CTR = I.CD_CTR 
WHERE
    I.CD_TRIB='51'
    AND EST_NF_ENT_DANFE_PROVISORIO.DT_EMIS_NF >='2016-08-01'
GROUP BY
	I.CD_CTR,
	I.CD_PROD


INSERT INTO #RSNFENTRADA
SELECT
	EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR,
	EST_NF_ENT_IT.CD_EMP, 
	EST_NF_ENT_IT.CD_FILIAL,
	EST_NF_ENT_IT.CD_NF,
	EST_NF_ENT_IT.CD_PROD
FROM
	EST_NF_ENT_IT INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT ON
	EST_NF_ENT_IT.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_EMP AND
	EST_NF_ENT_IT.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_FILIAL AND
	EST_NF_ENT_IT.CD_NF = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_NF 
	INNER JOIN #RSDANFE D ON
	EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR= D.CD_CTR
GROUP BY
	EST_NF_ENT_IT.CD_EMP,
	EST_NF_ENT_IT.CD_FILIAL,
	EST_NF_ENT_IT.CD_NF,	
	EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR,
	EST_NF_ENT_IT.CD_PROD

/*SELECT
	D.PERC_DIFERIMENTO,
	D.VLR_ICMS_DIFERIMENTO,
	D.VLR_ICMS_OP,
	IT.PERC_DIFERIMENTO,
	IT.VLR_ICMS_DIFERIMENTO,
	IT.VLR_ICMS_OP
FROM
	#RSDANFE D INNER JOIN #RSNFENTRADA E ON
	D.CD_CTR = E.CD_CTR AND
	D.CD_PROD = E.CD_PROD
	INNER JOIN EST_NF_ENT_IT IT ON
	E.CD_EMP = IT.CD_EMP AND
	E.CD_FILIAL =IT.CD_FILIAL AND
	E.CD_NF = IT.CD_NF AND
	E.CD_PROD = IT.CD_PROD
*/
--DEPOIS DE CONFERIDO APLICAR PRODUTOS DA ENTRADA
UPDATE
	IT 
SET 
	IT.PERC_DIFERIMENTO=D.PERC_DIFERIMENTO,
	IT.VLR_ICMS_DIFERIMENTO=D.VLR_ICMS_DIFERIMENTO,
	IT.VLR_ICMS_OP = D.VLR_ICMS_OP
FROM
	#RSDANFE D INNER JOIN #RSNFENTRADA E ON
	D.CD_CTR = E.CD_CTR AND
	D.CD_PROD = E.CD_PROD
	INNER JOIN EST_NF_ENT_IT IT ON
	E.CD_EMP = IT.CD_EMP AND
	E.CD_FILIAL =IT.CD_FILIAL AND
	E.CD_NF = IT.CD_NF AND
	E.CD_PROD = IT.CD_PROD

DROP TABLE #RSNFENTRADA
DROP TABLE #RSDANFE