/****** Object:  View [dbo].[V_PAINEL_NFE_EST_NF_SAI_ERRO_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_EST_NF_SAI_ERRO_ANALITICO]')) 
  DROP VIEW [dbo].[V_PAINEL_NFE_EST_NF_SAI_ERRO_ANALITICO] 

GO 

--SELECT * FROM V_PAINEL_NFE_EST_NF_SAI_ERRO_ANALITICO 
CREATE VIEW V_PAINEL_NFE_EST_NF_SAI_ERRO_ANALITICO  
AS
SELECT V_EST_NF_SAI_CAB.CD_FILIAL AS filialOrigemId,
       (CASE
            WHEN V_EST_NF_SAI_CAB.DEST_ORIG=0
                 AND V_EST_NF_SAI_CAB.CD_FILIAL_CLI > 0 THEN V_EST_NF_SAI_CAB.CD_FILIAL_CLI
            ELSE V_EST_NF_SAI_CAB.CD_CLI
        END) AS filialDestinoId,
       V_EST_NF_SAI_CAB.NM_DEST AS filialDestinoNome,
       V_EST_NF_SAI_CAB.NF_NF AS numeroNfe,
       V_EST_NF_SAI_CAB.CD_NF AS codigoControle,
       V_EST_NF_SAI_CAB.DT_EMI_NF AS data,
       V_EST_NF_SAI_CAB.DS_MOV_OP_USUAL AS tipoMovimentacao,
       EST_NF_SAI_ERROS_VALIDACAO.ERROS_VALIDACAO AS erroValidacao,
       V_EST_NF_SAI_CAB.VLR_NF AS valor,
       ISNULL(EST_NF_SAI_ERROS_VALIDACAO.VERSAO_APLIC, '') AS versaoAplicativo
FROM V_EST_NF_SAI_CAB
INNER JOIN EST_NF_SAI_ERROS_VALIDACAO ON V_EST_NF_SAI_CAB.CD_EMP = EST_NF_SAI_ERROS_VALIDACAO.CD_EMP
AND V_EST_NF_SAI_CAB.CD_FILIAL = EST_NF_SAI_ERROS_VALIDACAO.CD_FILIAL
AND V_EST_NF_SAI_CAB.CD_NF = EST_NF_SAI_ERROS_VALIDACAO.CD_NF
INNER JOIN EST_NF_SAI_PENDENCIA ON V_EST_NF_SAI_CAB.CD_EMP = EST_NF_SAI_PENDENCIA.CD_EMP
AND V_EST_NF_SAI_CAB.CD_FILIAL = EST_NF_SAI_PENDENCIA.CD_FILIAL
AND V_EST_NF_SAI_CAB.CD_NF = EST_NF_SAI_PENDENCIA.CD_NF
WHERE V_EST_NF_SAI_CAB.CD_EMP = 1
  AND EST_NF_SAI_ERROS_VALIDACAO.STS_ERRO = 0