ALTER PROCEDURE P_EST_ARV_MERC_MIX_ANALISE_VENDAS (@CD_EMP INT=1,@MES INT = NULL, @ANO INT = NULL) AS 
--EXEC P_EST_ARV_MERC_MIX_ANALISE_VENDAS 1,8,2016
SET NOCOUNT ON;  
DECLARE @DT_ATUAL DATETIME
SET @DT_ATUAL=GETDATE()
IF  @MES IS NULL                 
BEGIN                
 SET @MES = MONTH (@DT_ATUAL-1)
 SET @ANO = YEAR  (@DT_ATUAL-1)
END                
--INSERINDO REGISTROS

DELETE FROM EST_ARV_MERC_MIX_ANALISE_VENDAS WHERE MES = @MES AND ANO = @ANO
DELETE FROM EST_ARV_MERC_MIX_ANALISE_VENDAS_FILIAL WHERE MES = @MES AND ANO = @ANO

INSERT INTO EST_ARV_MERC_MIX_ANALISE_VENDAS
SELECT 
	IT.CD_EMP,
	IT.CD_PROD,
	@ANO ANO,
	@MES MES,
	SUM(IT.QT_IT), 
	SUM(CASE WHEN (IT.TOT_IT - IT.VLR_DESC_TOT_RAT) > 0 THEN 
		IT.TOT_IT - IT.VLR_DESC_TOT_RAT
	ELSE
		0
	END) AS TOT_IT,
	@DT_ATUAL
FROM
	PDV_VD_IT IT INNER JOIN PDV_VD V ON
	IT.CD_EMP = V.CD_EMP AND
	IT.CD_FILIAL = V.CD_FILIAL AND
	IT.CD_VD = V.CD_VD AND
	IT.DT_VD = V.DT_VD 	
	INNER JOIN PRC_FILIAL FIL ON 
	IT.CD_EMP = FIL.CD_EMP AND 
	IT.CD_FILIAL = FIL.CD_FILIAL
WHERE 
	IT.CD_EMP = @CD_EMP
	AND FIL.FLAG_FILIAL_NAO_PARTICP_MIX = 0 
	AND MONTH(IT.DT_VD) = @MES 
	AND YEAR(IT.DT_VD) = @ANO
	AND V.ST_VD=0
	AND IT.ST_IT=1
GROUP BY 
	IT.CD_EMP,
	IT.CD_PROD




INSERT INTO EST_ARV_MERC_MIX_ANALISE_VENDAS_FILIAL
SELECT 
	IT.CD_EMP,
	IT.CD_FILIAL,
	IT.CD_PROD,
	@ANO ANO,
	@MES MES,
	SUM(IT.QT_IT), 
	SUM(CASE WHEN (IT.TOT_IT - IT.VLR_DESC_TOT_RAT) > 0 THEN 
		IT.TOT_IT - IT.VLR_DESC_TOT_RAT
	ELSE
		0
	END) AS TOT_IT,
	@DT_ATUAL
FROM
	PDV_VD_IT IT INNER JOIN PDV_VD V ON
	IT.CD_EMP = V.CD_EMP AND
	IT.CD_FILIAL = V.CD_FILIAL AND
	IT.CD_VD = V.CD_VD AND
	IT.DT_VD = V.DT_VD 	
	INNER JOIN PRC_FILIAL FIL ON 
	IT.CD_EMP = FIL.CD_EMP AND 
	IT.CD_FILIAL = FIL.CD_FILIAL
WHERE 
	IT.CD_EMP = @CD_EMP
	AND FIL.FLAG_FILIAL_NAO_PARTICP_MIX = 0 
	AND MONTH(IT.DT_VD) = @MES 
	AND YEAR(IT.DT_VD) = @ANO
	AND V.ST_VD=0
	AND IT.ST_IT=1
GROUP BY 
	IT.CD_EMP,
	IT.CD_FILIAL,
	IT.CD_PROD
