call spQuery_Estado_Cuenta_Cabecera(1);

DROP PROCEDURE IF EXISTS spQuery_Estado_Cuenta_Cabecera;
CREATE PROCEDURE spQuery_Estado_Cuenta_Cabecera(
  varCliente  int
  )
BEGIN
  select A.CCLI, A.CLIENTE, A.DIRECCION, B.ULT_COMPRA, A.ULT_PAGO, SALDO
  from
    (
    select id_cliente as CCLI, nombre as CLIENTE, DIRECCION,
    (select max(fecha) from _sv_pago where id_cliente = varCliente and _estado='A') as ULT_PAGO
    from _sv_cliente
    where id_cliente = varCliente
    ) A
  left join
    (
    select V.id_cliente as CCLI,
    SUM(saldo) as SALDO,
    MAX(V.fecha_emision) as ULT_COMPRA
    from _sv_venta V    
    where V._estado = 'A'
    and V.estado <> 'AN'
    and V.id_cliente = varCliente
    group by V.id_cliente
    ) B
  on A.CCLI = B.CCLI;
END;