--/****** Object:  View [dbo].[V_EST_PROD_VD_MESES]    Script Date: 08/15/2012 09:49:19 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_EST_PROD_VD_MESES]'))
DROP VIEW [dbo].[V_EST_PROD_VD_MESES]
GO
GO
CREATE VIEW V_EST_PROD_VD_MESES
AS
SELECT
	CD_EMP,
	CD_PROD,
	SUM(QT_VD_ATUAL) AS QT_VD_ATUAL,
	SUM(VLR_VD_ATUAL) AS VLR_VD_ATUAL,
	SUM(QT_VD_01) AS QT_VD_01,
	SUM(VLR_VD_01) AS VLR_VD_01,
	SUM(QT_VD_02) AS QT_VD_02,
	SUM(VLR_VD_02) AS VLR_VD_02,
	SUM(QT_VD_03) AS QT_VD_03,
	SUM(VLR_VD_03) AS VLR_VD_03
FROM
(SELECT
	CD_EMP,
	CD_PROD,
	ANO,
	MES,
	QT_VD AS QT_VD_ATUAL,
	VLR_VD  AS VLR_VD_ATUAL,
	0 AS  QT_VD_01,
	0 AS VLR_VD_01,
	0 AS QT_VD_02,
	0 AS VLR_VD_02,
	0 AS QT_VD_03,
	0 AS VLR_VD_03
FROM
	EST_PROD_VD
WHERE
	ANO=YEAR(GETDATE())
	AND MES=MONTH(GETDATE())
UNION ALL
SELECT
	CD_EMP,
	CD_PROD,
	ANO,
	MES,
	0 AS  QT_VD_ATUAL,
	0 AS QT_VD_ATUAL,
	QT_VD AS  QT_VD_01,
	VLR_VD AS VLR_VD_01,
	0 AS QT_VD_02,
	0 AS VLR_VD_02,
	0 AS QT_VD_03,
	0 AS VLR_VD_03
FROM
	EST_PROD_VD
WHERE
	ANO=YEAR(DATEADD(MONTH,-1,GETDATE()))
	AND MES=MONTH(DATEADD(MONTH,-1,GETDATE()))
UNION ALL
SELECT
	CD_EMP,
	CD_PROD,
	ANO,
	MES,
	0 AS  QT_VD_ATUAL,
	0 AS VLR_VD_ATUAL,
	0 AS  QT_VD_01,
	0 AS VLR_VD_01,
	QT_VD AS QT_VD_02,
	VLR_VD AS VLR_VD_02,
	0 AS QT_VD_03,
	0 AS VLR_VD_03
FROM
	EST_PROD_VD
WHERE
	ANO=YEAR(DATEADD(MONTH,-2,GETDATE()))
	AND MES=MONTH(DATEADD(MONTH,-2,GETDATE()))
UNION ALL
SELECT
	CD_EMP,
	CD_PROD,
	ANO,
	MES,
	0 AS  QT_VD_ATUAL,
	0 AS VLR_VD_ATUAL,
	0 AS  QT_VD_01,
	0 AS VLR_VD_01,
	0 AS QT_VD_L02,
	0 AS VLR_VD_02,
	QT_VD AS QT_VD_03,
	VLR_VD AS VLR_VD_03
FROM
	EST_PROD_VD
WHERE
	ANO=YEAR(DATEADD(MONTH,-3,GETDATE()))
	AND MES=MONTH(DATEADD(MONTH,-3,GETDATE()))) Rs
GROUP BY
	CD_EMP,
	CD_PROD