Skip to content
Advertisement

Joining back on the same table in SQL server

I have a table like below

enter image description here

And the output I require is

Output

The match is defined on the basis of PO number. If PO number exists in both the sources then it should be match else only in AAP and only in SNW respectively. Can this be achieved?

Thanks, Ani

Advertisement

Answer

select *,
    case when min(SOURCE) over (partition by ID) <> max(SOURCE) over (partition by ID)
        then 'Match' else 'Only in ' + SOURCE end as Status
from T

or

select *,
    case when exists
    (
        select 1 from T t2
        where t2.ID = T.ID and t2.SOURCE <> T.SOURCE
    )
        then 'Match' else 'Only in ' + SOURCE end as Status
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement