Question

I have two tables.

Table 1 : 'DQ' is the golden source of information,

Table 2 : 'PS' is whats currently in the DB.

What I would like to do is compare the DQ table to whats inthe PS Table and derive an outcome

Table 1 :

Select
 Account_Number,
 Sec_id
from DQ
 where account_number = '1234'

This returns the following data set

Account_Number  Sec_id
1234    AAA
1234    BBB
1234    CCC
1234    DDD
1234    FFF

Table 2

    select
     Account_Code__C,
     IS_c
    from ps
where Account_Code__C= '1234'

Returns the following data set.

Account_Code__C IS_c
1234    AAA
1234    BBB
1234    CCC
1234    DDD
1234    EEE

As you can see although the column names between two tables are different there is a match

dq.Account_Number =  PS.Account_Code__C
DQ.Sec_id         = Dq.IS_c

As you can see in the 'DQ' table I have an additional sec_id of FFF which is not in 'PS' table. The expected outcome I am looking for is as follows:

table

Looking forward to your help

i have attempted to do an outter join, however i was returning 28 rows

Was it helpful?

Solution

I always recommend brushing up on joins if you're encountering unexpected results. Your FULL JOIN probably returns multiple results might be a product of bad join conditions or duplicate results in each sub-query. I would limit these by grouping results in each sub-query so we ensure distinct results.

Also, line 6 in your example spreadsheet illustrates the problem; Account_Code_C should probably be blank if IS_c is blank, since there should be a full row returned from each source. I prettied this up with an ISNULL.

Here's how I would write this: (remove all lines with @Account_Code to get results for all account codes)

DECLARE @Account_Code INT
SET @Account_Code = 1234

SELECT DISTINCT ISNULL(b.Account_Code_C, a.Sec_id) as Account_Code_C
    , b.IS_c
    , a.Sec_id
    , case when b.IS_c IS NULL and a.Sec_id IS NULL then 'Da Fuq?'
    when b.Is_c IS NULL then 'Adding'
    when a.Sec_id is NULL then 'Investigation'
    else 'Match' --both have values, our join ensures they're the same
    end
FROM (
    SELECT DISTINCT Account_Number
    , Sec_id
    FROM DQ
    WHERE 1=1
    AND Account_Number=@Account_Code
)a
FULL JOIN (
    SELECT DISTINCT Account_Code__C, IS_c
    FROM PS
    WHERE 1=1
    AND Account_Code__C=@Account_Code
)b ON a.Sec_id=b.IS_c AND a.Account_Number=b.Account_Code__C
WHERE 1=1

OTHER TIPS

You'd want a left join I believe.

Select Account_Number, Sec_id from DQ
left join PS on DQ.sec_id=PS.IS_c
where account_number = '1234' 
AND account_code__c='1234'

Something like this although you may have to adjust it a little.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top