4

I have 2 tables as follows:

| Table 1             | Table 2
| Column 1 | Column 2 | Column 1    
|----------|----------|---------
|c1        |v1        | v1
|c1        |v2        | v2
|c1        |v4        | v3
|c2        |v2        | v4
|c2        |v7        | v5
|c3        |v1        | v6
|c3        |v3        | v7
|c3        |v4        
|c3        |v6        

I would like to "outer join" them per group to get the following result

 | Column 1 | Column 2
 |----------|---------
 |c1        |v3       
 |c1        |v5       
 |c1        |v6
 |c1        |v7                 
 |c2        |v1       
 |c2        |v3      
 |c2        |v4       
 |c2        |v5      
 |c2        |v6           
 |c3        |v2     
 |c3        |v5       
 |c3        |v7       

Essentially finding every value in table 2 that does not match in table 1 by its group, in this scenario being column 1.

My initial attempts of joining the 2 tables doesn't seem to yield the results I'm after eg:

SELECT * FROM 
Table1 T1
FULL OUTER JOIN Table2 T2 on t1.Column2 = t2.Column1
where t1.column1 is null
ekad
  • 14,436
  • 26
  • 44
  • 46
Breaker
  • 319
  • 2
  • 11

3 Answers3

2

Also, you can use EXCEPT:

SELECT DISTINCT t1.c1
               ,t2.c1
FROM @t1 t1
CROSS APPLY @t2 t2
EXCEPT
SELECT *
FROM @t1
gotqn
  • 42,737
  • 46
  • 157
  • 243
1

This should do what you need it to:

declare @t1 table(c1 nvarchar(5),c2 nvarchar(5));
declare @t2 table(c1 nvarchar(5));

insert into @t1 values ('c1','v1'),('c1','v2'),('c1','v4'),('c2','v2'),('c2','v7'),('c3','v1'),('c3','v3'),('c3','v4'),('c3','v6');

insert into @t2 values ('v1'),('v2'),('v3'),('v4'),('v5'),('v6'),('v7');

select ta.c1
        ,t2.c1 as c2
from @t2 t2
    cross apply (select distinct c1 from @t1) ta
    left join @t1 t1
        on(t2.c1 = t1.c2
            and ta.c1 = t1.c1
            )
where t1.c1 is null
order by ta.c1
        ,ta.c1;

Output:

c1  c2
------
c1  v3
c1  v5
c1  v6
c1  v7
c2  v1
c2  v3
c2  v4
c2  v5
c2  v6
c3  v2
c3  v5
c3  v7
iamdave
  • 12,023
  • 3
  • 24
  • 53
1

Produce all combinations first and left join on first table to figure out what is missing:

select distinct t1.c1, t2.c1 
from @t1 t1 
cross join @t2 t2
left join @t1 t on t1.c1 = t.c1 and t2.c1 = t.c2
where t.c1 is null
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75