IF not OBJECT_ID('V_EST_NF_ENT_NF_SAI_IT') IS NULL
	BEGIN
		DROP VIEW V_EST_NF_ENT_NF_SAI_IT
	END
go
CREATE  VIEW 
	[dbo].[V_EST_NF_ENT_NF_SAI_IT]  
AS  
SELECT
	dbo.EST_NF_ENT_NF_SAI.CD_EMP, 
	dbo.EST_NF_ENT_NF_SAI.CD_FILIAL, 
	dbo.EST_NF_ENT_NF_SAI.CD_NF_ENT, 
	dbo.EST_NF_SAI_IT.CD_PROD,   
    SUM(dbo.EST_NF_SAI_IT.QT_IT) AS QT_IT_DEV, 
	dbo.EST_NF_SAI.STS_NF
FROM
	dbo.EST_NF_SAI
	INNER JOIN dbo.EST_NF_ENT_NF_SAI ON
		dbo.EST_NF_SAI.CD_EMP = dbo.EST_NF_ENT_NF_SAI.CD_EMP AND
		dbo.EST_NF_SAI.CD_FILIAL = dbo.EST_NF_ENT_NF_SAI.CD_FILIAL
		AND dbo.EST_NF_SAI.CD_NF = dbo.EST_NF_ENT_NF_SAI.CD_NF_SAI 
	INNER JOIN  dbo.EST_NF_SAI_IT ON 
		dbo.EST_NF_SAI.CD_EMP = dbo.EST_NF_SAI_IT.CD_EMP AND
		dbo.EST_NF_SAI.CD_FILIAL = dbo.EST_NF_SAI_IT.CD_FILIAL
		AND dbo.EST_NF_SAI.CD_NF = dbo.EST_NF_SAI_IT.CD_NF
    INNER JOIN GLB_MOV_OP ON
		EST_NF_SAI.CD_NT_MOV = GLB_MOV_OP.CD_MOV_OP
WHERE
	GLB_MOV_OP.TP_MOV IN (11, 15, 17, 18, 19, 20, 31, 41, 57, 59, 60, 62) --CONSIDERA APENAS AS SAIDAS POR DEVOLUCAO
GROUP BY
	dbo.EST_NF_ENT_NF_SAI.CD_EMP,
	dbo.EST_NF_ENT_NF_SAI.CD_FILIAL,
	dbo.EST_NF_ENT_NF_SAI.CD_NF_ENT, 
	dbo.EST_NF_SAI_IT.CD_PROD,
	dbo.EST_NF_SAI.STS_NF
