Search code examples
sql-servert-sqlinner-joinunion

How can I find different elements between two columns (generated by two subqueries)?


My subqueries produce a result like this:

coulmn1    column2
a          d
b          z1000
c          c
d
1
2
z1000      k

I want to know the different elements in both sets. column1 ={ a,b,c, 1,2,d, z1000,.....} column 2 ={ d,c,z1000,k......} The result I want is ={ a,k,1,2,....} hope I made it clear ..please let me know how could I do that..?


Solution

  • One method is full outer join:

    select coalesce(t1.col1, t2.col2)
    from t t1 full join
         t t2
         on t1.col1 = t2.col2
    where t1.col1 is null or t2.col2 is null;
    

    Another method doesn't require running the subquery twice;

    select v.col
    from t cross apply
         (values (t.col1, 1), (t.col2, 2)) v(col, which)
    group by v.col
    having min(v.which) = max(v.which);