/****** Object:  View [dbo].[V_PAINEL_NFE_PDV_VD_DEV_EST_PROD_IMP_ANALITICO]    Script Date: 03/10/2018 11:00:00 ******/ 
IF EXISTS (SELECT * 
           FROM   SYS.VIEWS 
           WHERE  OBJECT_ID = 
      Object_id(N'[dbo].[V_PAINEL_NFE_PDV_VD_DEV_EST_PROD_IMP_ANALITICO]')) 
  DROP VIEW [dbo].[V_PAINEL_NFE_PDV_VD_DEV_EST_PROD_IMP_ANALITICO] 

GO 

--SELECT * FROM V_PAINEL_NFE_PDV_VD_DEV_EST_PROD_IMP_ANALITICO 
CREATE VIEW V_PAINEL_NFE_PDV_VD_DEV_EST_PROD_IMP_ANALITICO  
AS
SELECT PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL AS filialOrigemId,
       PDV_VD.NR_ECF AS numeroEcf,
       PDV_VD.CD_CX AS caixa,
       PDV_VD_DEV_NCC.CD_CLI AS clienteId,
       RC_CLI.RZ_CLI AS clienteNome,
       EST_PROD_IMP.DT_CAD as dataCadastro,
       PDV_VD.DT_VD AS data,
       SUM((PDV_VD_DEV_EST_PROD_IMP.QT_IT * PDV_VD_DEV_EST_PROD_IMP.VLR_IT)) AS valor
FROM PDV_VD_DEV_EST_PROD_IMP
INNER JOIN PDV_VD ON PDV_VD_DEV_EST_PROD_IMP.CD_VD = PDV_VD.CD_VD
AND PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL = PDV_VD.CD_FILIAL
AND PDV_VD_DEV_EST_PROD_IMP.CD_EMP = PDV_VD.CD_EMP
INNER JOIN EST_PROD_IMP ON PDV_VD_DEV_EST_PROD_IMP.CD_EMP = EST_PROD_IMP.CD_EMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL = EST_PROD_IMP.CD_FILIAL
AND PDV_VD_DEV_EST_PROD_IMP.CD_IMP = EST_PROD_IMP.CD_IMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_PROD = EST_PROD_IMP.CD_PROD
LEFT OUTER JOIN PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP ON PDV_VD_DEV_EST_PROD_IMP.CD_EMP = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_EMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL
AND PDV_VD_DEV_EST_PROD_IMP.CD_VD = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_VD
AND PDV_VD_DEV_EST_PROD_IMP.CD_IMP = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_IMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_PROD = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_PROD
AND PDV_VD_DEV_EST_PROD_IMP.CD_IT = PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_IT
LEFT OUTER JOIN PDV_VD_DEV_NCC ON PDV_VD_DEV_NCC_PDV_VD_DEV_EST_PROD_IMP.CD_CTR_NCC = PDV_VD_DEV_NCC.CD_CTR_NCC
LEFT OUTER JOIN RC_CLI ON PDV_VD_DEV_NCC.CD_CLI = RC_CLI.CD_CLI
AND PDV_VD_DEV_NCC.CD_EMP = RC_CLI.CD_EMP
INNER JOIN PDV_VD_DEV_EST_PROD_IMP_PEND_NF ON PDV_VD_DEV_EST_PROD_IMP.CD_EMP = PDV_VD_DEV_EST_PROD_IMP_PEND_NF.CD_EMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL = PDV_VD_DEV_EST_PROD_IMP_PEND_NF.CD_FILIAL
AND PDV_VD_DEV_EST_PROD_IMP.CD_IMP = PDV_VD_DEV_EST_PROD_IMP_PEND_NF.CD_IMP
AND PDV_VD_DEV_EST_PROD_IMP.CD_PROD = PDV_VD_DEV_EST_PROD_IMP_PEND_NF.CD_PROD
AND PDV_VD_DEV_EST_PROD_IMP.CD_IT = PDV_VD_DEV_EST_PROD_IMP_PEND_NF.CD_IT
GROUP BY PDV_VD_DEV_EST_PROD_IMP.CD_EMP,
         PDV_VD_DEV_EST_PROD_IMP.CD_FILIAL,
         PDV_VD.CD_CX,
         PDV_VD.DT_VD,
         PDV_VD.CD_VD,
         PDV_VD.NR_ECF,
         EST_PROD_IMP.DT_CAD,
         PDV_VD_DEV_NCC.CD_CLI,
         PDV_VD.VLR_LIQ_VD,
         RC_CLI.RZ_CLI,
         PDV_VD_DEV_NCC.CD_CLI,
         NM_COMPRADOR,
         PDV_VD_DEV_NCC.CD_CTR_NCC