IF EXISTS(SELECT  * FROM  sys.views WHERE object_id = OBJECT_ID(N'[dbo].V_CONCILIACAO_CARTOES_LINX_CONCILIADOR_RC_ADM_CARTAO'))
    BEGIN
        DROP VIEW  [dbo].[V_CONCILIACAO_CARTOES_LINX_CONCILIADOR_RC_ADM_CARTAO];
    END;
GO

CREATE VIEW V_CONCILIACAO_CARTOES_LINX_CONCILIADOR_RC_ADM_CARTAO
AS
SELECT 
	C.CD_FILIAL
	,C.IDT_LOTE_REDE
	,MAX(T.CD_ADM_CARTAO)CD_ADM_CARTAO 
	,MAX(CL.CD_CLI)CD_CLI 
	,MAX(A.FLAG_OPERADORA_NAO_DEFINIDA) FLAG_OPERADORA_NAO_DEFINIDA
	,MAX(A.TP_ADM) TP_ADM
FROM 
	CONCILIACAO_CARTOES_LINX_CONCILIADOR C
	JOIN CONCILIACAO_CARTOES_FINAL  F ON 
	C.CD_CTR  =F.CD_CTR_CONCILIADOR
	JOIN PDV_VD_TEF T ON 
	F.CD_CTR_PDV_VD_TEF  =T.CD_CTR
	JOIN RC_ADM_CARTAO A ON 
	T.CD_ADM_CARTAO  = A.CD_ADM_CARTAO
	JOIN RC_ADM_CARTAO_RC_CLI CL ON 
	T.CD_ADM_CARTAO  = CL.CD_ADM_CARTAO
GROUP BY 
	C.CD_FILIAL, C.IDT_LOTE_REDE
UNION ALL 

SELECT 
	C.CD_FILIAL
	,C.IDT_LOTE_REDE
	,MAX(R.CD_ADM_CARTAO)CD_ADM_CARTAO 
	,MAX(CL.CD_CLI)CD_CLI 
	,MAX(FLAG_OPERADORA_NAO_DEFINIDA) FLAG_OPERADORA_NAO_DEFINIDA
	,MAX(A.TP_ADM) TP_ADM
FROM 
	CONCILIACAO_CARTOES_LINX_CONCILIADOR C
	JOIN CONCILIACAO_CARTOES_FINAL  F ON 
	C.CD_CTR  =F.CD_CTR_CONCILIADOR
	JOIN PDV_CUPOM_NAO_FISCAL_TEF  T  ON
    f.CD_CTR_PDV_VD_TEF = t.Cd_Ctr

	JOIN PDV_RECBTO_TEF R ON 
    T.CD_EMP        =  R.CD_EMP AND
    T.CD_FILIAL     =  R.CD_FILIAL AND
    T.CD_RECTO_TEF  =  R.CD_RECTO_TEF 
	JOIN RC_ADM_CARTAO A ON 
	R.CD_ADM_CARTAO  = A.CD_ADM_CARTAO
	JOIN RC_ADM_CARTAO_RC_CLI CL ON 
	R.CD_ADM_CARTAO  = CL.CD_ADM_CARTAO
GROUP BY 
	C.CD_FILIAL, C.IDT_LOTE_REDE