SELECT
        `cta`.`id` as `id_cta_cte`,
        `ta`.`id` AS `tipo_asiento_id`,
        (CASE
             WHEN (`ta`.`id` = 2) THEN 'COBRANZA'
             ELSE 'PAGO'
            END) AS `operacion`,
        `cta`.`saldo_id` AS `saldo_id`,
        `cta`.`comentario` AS `comentario`,
        `cta`.`person_id`,
        `cta`.`person_id_relationed`,
        `periods`.`id` as `period_id`,
        `periods`.`code` as `periodo_code`,
        `ta`.`nombre` AS `asiento`,
        `cta`.`plan_cuenta_id` AS `plan_cuenta_id`,
        `pc`.`nombre` AS `cuenta`,
        `receipts`.`id` AS `receipt_id`,
        `cta`.`fecha` AS `fecha`,
        `p`.`field_name1` AS `empresa_titular`,
        `per_rela`.`field_name1` AS `empresa_relacionada`,
        (CASE
            WHEN (`cta`.`saldo_id` = 1) THEN `cta`.`total`
            ELSE 0
        END) AS `DEBE`,
        (CASE
            WHEN (`cta`.`saldo_id` = 2) THEN `cta`.`total`
            ELSE 0
        END) AS `HABER`
    FROM `cta_cte_cliente` `cta`
        JOIN `conta_tipo_saldos` `ts` ON `cta`.`saldo_id` = `ts`.`id`
        JOIN `persons` `p` ON `cta`.`person_id` = `p`.`id`
        JOIN `persons` `per_rela` ON `cta`.`person_id_relationed` = `per_rela`.`id`
        JOIN `periods` ON `cta`.`period_id` = `periods`.`id`
        LEFT JOIN `receipts` ON `cta`.`receipt_id` = `receipts`.`id`
        JOIN `conta_tipo_asientos` `ta` ON `cta`.`tipo_asiento_id` = `ta`.`id`
        JOIN `conta_plan_cuenta` `pc` ON `cta`.`plan_cuenta_id` = `pc`.`id`

    ORDER BY `cta`.`id` , `cta`.`id` , `cta`.`saldo_id` , `p`.`field_name1`