简体   繁体   中英

Missing rows that are only on one table on FULL OUTER JOIN in PostgreSQL

I have 2 tables remittance and draft where I'm trying to find the difference between what was remitted and drafted.

This is what I have so far, but it doesn't give me the records that are only on one of the tables

SELECT remittance.loan_no, remittance.inv_loan_no, remittance.ll_remittance,
       draft.fm_loan_number, draft.draft_amount,
       (remittance.ll_remittance) - (draft.draft_amount) AS difference
       
FROM    remittance FULL JOIN draft

ON      remittance_.inv_loan_no = draft.fm_loan_number

WHERE  (remittance.ll_remittance) - (draft.draft_amount)<> 0.00;

Could it be because I when I do the difference the missing remittance or draft amounts have null values in them and that's why I'm not getting any results for the difference.

I thought FULL JOIN would give me the loans that are only on one of the tables and NULL in other tables column.

Thank you,

Here is the sample data:

Remittance Table, Draft Table, Query Results

I have highlighted the loans in red that are not showing up in the Query Results

Could it be because I when I do the difference the missing remittance or draft amounts have null values in them and that's why I'm not getting any results for the difference.

Yes! Adding a where clause to a full join is always tricky because the filtering takes place on the joined data set.

However, I don't think there should be any problems in placing that difference query in the on clause instead.

SELECT remittance.loan_no, remittance.inv_loan_no, remittance.ll_remittance,
       draft.fm_loan_number, draft.draft_amount,
       (remittance.ll_remittance) - (draft.draft_amount) AS difference
       
FROM    remittance FULL JOIN draft

ON      remittance_.inv_loan_no = draft.fm_loan_number
        AND (remittance.ll_remittance) - (draft.draft_amount)<> 0.00;

If you have only one row in each table for each loan, then coalesce() suffices for your purposes:

SELECT r.loan_no, r.inv_loan_no, r.ll_remittance,
       d.fm_loan_number, d.draft_amount,
       coalesce(r.ll_remittance, 0) - coalesce(d.draft_amount, 0) AS difference       
FROM  remittance r FULL JOIN
      draft d
      ON r.inv_loan_no = d.fm_loan_number
WHERE coalesce(r.ll_remittance, 0) <> coalesce(d.draft_amount, 0);

If there are multiple rows, then you will need to pre-aggregate.

Here is a SQL Fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM