Building distinct Column from a common column from two tables

casedistinct

Good afternoon team,

hope all is well

I am hoping you can help me.

I have following two tables "GODS.DQ_TOBE" & "GODS.DQ_CURRENT". Within each table there is a common column called "Account_code__C". What i would like to do is build a column called Account_code__C which houses the distinct account codes from both of these tables. i would then like to produce two other columns to tell me what table the Account_code__C was found in.

Desired outcome would look something like this

OutCome

SELECT Account_code__C FROM GODS.DQ_TOBE
Select Account_code__C from GODS.DQ_CURRENT

Best Answer

The following code should get you the result for MS SQL or MySQL:

select distinct f.Account_code__C,
case when a.Account_code__C<>'' then 'Y' else 'N' end AS DQ_TOBE, 
case when b.Account_code__C<>'' then 'Y' else 'N' end AS DQ_CURRENT
from (
    SELECT Account_code__C FROM GODS.DQ_TOBE
    union
    SELECT Account_code__C FROM GODS.DQ_CURRENT
) f
left join GODS.DQ_TOBE a on a.Account_code__C=f.Account_code__C
left join GODS.DQ_CURRENT b on b.Account_code__C=f.Account_code__C