call spQuery_Pagos_CxC_Editar(1);

DROP PROCEDURE IF EXISTS spQuery_Pagos_CxC_Editar;
CREATE PROCEDURE spQuery_Pagos_CxC_Editar(	
	varPago  int
)
BEGIN
  select P.id_pago_cxc as CPAG, 
  P.id_cliente as CCLI, C.nombre as CLIENTE, 
  P.id_forma_pago as CTIP, TP.nombre as TIPO, P.nro_doc_pago as NPAGO, 
  date_format(P.fecha,'%d/%m/%Y') as FECHA, P.MONTO, 
  CONCAT(TV.abrev,' - ', V.nro_serie,'-',V.nro_preimpreso) AS DOCUMENTO,
  date_format(V.fecha_emision,'%d/%m/%Y') as FECHA_EMI,
  V.total AS MONTO_DOC,
  V.total - IFNULL((select sum(monto) as PAGOS from _sv_pago_cxc Z where Z._estado='A' and Z.id_venta=P.id_venta),0) AS SALDO,
  (select sum(monto) as PAGOS from _sv_pago_cxc Z where Z._estado='A' and Z.id_venta=P.id_venta) as PAGOS,
  V.total - IFNULL((select sum(monto) as PAGOS from _sv_pago_cxc Z where Z._estado='A' and Z.id_venta=P.id_venta and Z.id_pago_cxc <> P.id_pago_cxc),0) AS SALDO_MAX
  from _sv_pago_cxc P 
  inner join _sv_forma_pago TP   ON P.id_forma_pago = TP.id_forma_pago 
  inner join _sv_cliente C          ON P.id_cliente = C.id_cliente 
  inner join _sv_venta V            ON P.id_venta = V.id_venta
  inner join _sv_tipo_doc_venta TV  ON V.id_tipo_doc = TV.id_tipo_doc
  where P._estado = 'A'
  and P.id_pago_cxc = varPago;
END;