SELECT
       *
FROM
(
    SELECT
        docnumber,
        SUM(amount) as diff
    FROM
    (
        SELECT 
            gltrans_docnumber as docnumber,
            SUM(gltrans_amount) AS amount
        FROM
        (
        SELECT
            gltrans_id,
            gltrans_source,
            CASE WHEN gltrans_doctype = 'SO' THEN
                split_part(gltrans_docnumber, '-', 1)
            WHEN gltrans_doctype = 'JE' THEN
                regexp_replace(gltrans_docnumber,'FIFO-(COHEAD|CMHEAD|INVCHEAD)-','')
            ELSE
                gltrans_docnumber

            END AS gltrans_docnumber,
            gltrans_misc_id,
            gltrans_amount

        FROM
            gltrans
        WHERE
            gltrans_date::date >= '2012-05-01'::date
            AND
            gltrans_accnt_id = (SELECT costcat_asset_accnt_id FROM costcat LIMIT 1)
            AND
            gltrans_doctype NOT IN ('PO', 'VO') -- ignore the PO
            AND
            NOT gltrans_deleted
            AND
            split_part(gltrans_docnumber, '-', 1) != 'COS'
            AND
            strpos(gltrans_docnumber, 'JE-IR-LANDCOST') = 0
        ) AS x

        GROUP BY gltrans_docnumber

        UNION ALL


        SELECT
            invhist_ordnumber as docnumber,
            SUM(invdetail_qty * invfifo_landedunitcost) AS amount
        FROM
        (
        SELECT
            CASE WHEN invhist_ordtype = 'SO' THEN
                split_part(invhist_ordnumber, '-', 1)
            ELSE
                invhist_ordnumber
            END AS invhist_ordnumber,
            invdetail_qty,
            invfifo_landedunitcost

        FROM
            invdetailview
        WHERE
            invhist_transdate::date >= '2012-05-01'::date
            AND
            invfifo_void = 0
            AND
            invhist_transtype NOT IN ('RP', 'RL') -- ignore the PO and the sum of RL should be 0, we can run (SELECT SUM(invdetail_qty) FROM invdetailview WHERE invhist_transtype = 'RL';) to confirm
        ) AS y

        GROUP BY invhist_ordnumber   
    ) z
GROUP BY docnumber
) zz

WHERE
    ABS(diff) > 1



