IF OBJECT_ID('V_CUPOMFISCAL_PBM') IS NOT NULL 
	DROP VIEW V_CUPOMFISCAL_PBM 
GO 

CREATE VIEW V_CUPOMFISCAL_PBM
AS
SELECT	VD.CD_EMP, VD.CD_FILIAL,VD.CD_CX,VD.DT_VD,VD.CD_VD,VD.NR_ECF, VD.ST_VD
        ,PBM.NR_AUTORIZACAO AS CD_AUTORIZACAO,COALESCE(CONV.CD_CONV,0) AS CD_CONV
        ,CASE WHEN COALESCE(VD.VLR_CONV_PBM,0) <> 0 THEN VD.VLR_CONV_PBM ELSE COALESCE(VD.VLR_CONV,0) END AS VLR_CONV
        ,COALESCE(PBM.CD_CLI_PBM,VD.CD_CLI,0) AS CD_CLI_CONV,CLI_CONV.CGC_CPF AS CGC_CONV, COALESCE(CLI_CONV.RZ_CLI, CONV.DS_CONV) AS NM_CONV
        ,IT.CD_IT,IT.QT_IT,IT.VLR_IT,IT.CD_PROD,PBM.VLR_PROD_CLI,PBM.VLR_REEMBOL AS VLR_PROD_REEMBOLSO,PBM.VLR_CONVENIO AS VLR_PROD_CONV
FROM    PDV_VD VD
INNER	JOIN  PDV_VD_IT IT	ON VD.CD_EMP = IT.CD_EMP AND VD.CD_FILIAL = IT.CD_FILIAL AND VD.CD_VD = IT.CD_VD AND VD.DT_VD = IT.DT_VD
INNER	JOIN  PDV_VD_IT_VD_PBM PBM ON PBM.CD_EMP = IT.CD_EMP AND PBM.CD_FILIAL = IT.CD_FILIAL AND PBM.CD_VD = IT.CD_VD AND PBM.CD_IT = IT.CD_IT
LEFT    JOIN  RC_CLI CLI_CONV ON PBM.CD_EMP = CLI_CONV.CD_EMP AND PBM.CD_CLI_PBM = CLI_CONV.CD_CLI
LEFT    JOIN  RC_CLI_CONV CONV ON CLI_CONV.CD_EMP = CONV.CD_EMP AND CLI_CONV.CD_CLI = CONV.CD_CLI
WHERE	CLI_CONV.ESP_CLI = 3