SELECT
    issued, 
    CAST(debtOut AS DECIMAL(10,2)) debtOut, 
    CAST(debtIn AS DECIMAL(10,2)) debtIn,
    ref, 
    companyFk, 
    priority
FROM (
    SELECT 
        ? AS issued, 
        SUM(amountUnpaid) AS debtOut, 
        NULL AS debtIn, 
        'Saldo Anterior' AS ref, 
        companyFk,
        0 as priority 
    FROM (
        SELECT SUM(amount) AS amountUnpaid, companyFk, 0 
            FROM invoiceOut io
            WHERE io.clientFk = ?
                AND io.issued < ?
            GROUP BY io.companyFk
        UNION ALL
        SELECT SUM(-1 * amountPaid), companyFk, 0 
            FROM receipt 
            WHERE clientFk = ?
                AND payed < ? 
            GROUP BY companyFk) AS transactions 
    GROUP BY companyFk
    UNION ALL
    SELECT 
            issued, 
            amount as debtOut, 
            NULL AS debtIn, 
            ref,
            companyFk,
            1 
        FROM invoiceOut 
        WHERE clientFk = ? 
            AND issued >= ?
    UNION ALL
    SELECT 
            r.payed, 
            NULL as debtOut, 
            r.amountPaid, 
            r.invoiceFk, 
            r.companyFk,
            0 
        FROM receipt r
        WHERE r.clientFk = ?
            AND r.payed >= ?) t 
    INNER JOIN `client` c ON c.id = ? 
HAVING debtOut <> 0 OR debtIn <> 0 
ORDER BY issued, priority DESC, debtIn;