
SELECT
        docnumber,
        total_gltrans,
        total_adjust,
        diff
FROM
(
    SELECT
            docnumber,
            SUM(gltrans_amount) AS total_gltrans,
            SUM(adjust_amount) AS total_adjust,
            SUM(gltrans_amount) + SUM(adjust_amount) AS diff
    FROM
    (
        SELECT
                reverse(regexp_replace(reverse(gltrans_docnumber),'^[0-9]{1,}-', '')) AS docnumber,            
                COALESCE(gltrans_amount,0) AS gltrans_amount,
                0 AS adjust_amount
        FROM
                gltrans
        WHERE
                gltrans_date >= '2013-09-01'::date
                AND
                gltrans_date < '2013-10-01'::date
                AND
                gltrans_docnumber NOT LIKE 'FIFO-COHEAD-%'
                AND
                gltrans_accnt_id = (SELECT costcat_shipasset_accnt_id FROM costcat LIMIT 1)
                AND
                gltrans_posted
                AND
                NOT gltrans_deleted
        
        UNION ALL

        SELECT
                replace(gltrans_docnumber,'FIFO-COHEAD-','') AS docnumber,
                0 AS gltrans_amount,
                COALESCE(gltrans_amount,0) AS adjust_amount
        FROM
                gltrans
        WHERE
                gltrans_date >= '2013-09-01'::date
                AND
                gltrans_date < '2013-10-01'::date
                AND
                gltrans_docnumber LIKE 'FIFO-COHEAD-%'
                AND
                gltrans_accnt_id = (SELECT costcat_shipasset_accnt_id FROM costcat LIMIT 1)
                AND
                gltrans_posted
                AND
                NOT gltrans_deleted
        
    ) AS x

    GROUP BY docnumber
    
) AS y


WHERE
    ABS(diff) > 1