SELECT 
    `pe`.`code` AS `periodo`,
    `pe`.`date_from` AS `Desde`,
    pc4.nombre as nivel1,
    pc3.nombre as nivel2,
    pc2.nombre as nivel3,
    pc1.nombre as nivel4,
    pc.nombre as nivel5,
    pc.tipo_cuenta_id,
    `bld`.`plan_cuenta_id` AS `plan_cuenta_id`,
    `bld`.`person_id` AS `person_id`,
    `pc`.`nombre` AS `cuenta`,
    sum((CASE
        WHEN (`bld`.`saldo_id` = 1) THEN `bld`.`monto`
        WHEN (`bld`.`saldo_id` = 2) THEN `bld`.`monto`*(-1)
    END)) AS `SALDO`
FROM
    `balance_libro_details` `bld`
    JOIN `balance_libro` `bl` ON `bld`.`balance_libro_id` = `bl`.`id`
    JOIN `conta_tipo_saldos` `ts` ON `bld`.`saldo_id` = `ts`.`id`
    JOIN `persons` `p` ON `bld`.`person_id` = `p`.`id`
    JOIN `periods` `pe` ON `bld`.`period_id` = `pe`.`id`
    JOIN `conta_tipo_asientos` `ta` ON `bl`.`conta_tipo_asiento_id` = `ta`.`id`
    left JOIN `conta_plan_cuenta` `pc` ON `bld`.`plan_cuenta_id` = `pc`.`id`
    left JOIN `conta_plan_cuenta` `pc1` ON `pc`.`padre` = `pc1`.`codigo`
    left JOIN `conta_plan_cuenta` `pc2` ON `pc1`.`padre` = `pc2`.`codigo`
    left JOIN `conta_plan_cuenta` `pc3` ON `pc2`.`padre` = `pc3`.`codigo`
    left JOIN `conta_plan_cuenta` `pc4` ON `pc3`.`padre` = `pc4`.`codigo`
where bld.person_id = 2123
and `pe`.`date_from` between '2017-09-01' and '2018-08-01'
group by `bld`.plan_cuenta_id
order by pc.codigo