Skip to content
Advertisement

How to identify non-existing keys with reference to a table that has all mandatory keys, SQL?

I have the table ‘Table01’ which contains the keys that should be mandatory:

id
1
2
3
4

And I also have the table ‘Table02’ which contains the records to be filtered:

id customer weight
1 a 100
2 a 300
3 a 200
4 a 45
1 b 20
2 b 100
3 b 17
1 c 80
4 c 90
2 d 30
3 d 30
4 d 50

So I want to identify which are the mandatory id’s that the table ‘Table02’ does not have, and in turn identify which is the ‘customer’ of each id’s that the table ‘Table02’ does not have.

The resulting table should look like this:

customer id
b 4
c 2
c 3
d 1

What I have tried so far is a ‘rigth join’.

proc sql;
create table table03 as
select
 b.id
from table02 a
right join table01 b
on a.id=b.id
where a.id is null;
run;

But that query is not identifying all the id’s that should be mandatory.

I hope someone can help me, thank you very much.

Advertisement

Answer

here is one way:

select cl.customerid , a.id
from
Table1 a
cross join 
( select customerid
  from table2 
  group by customerid
) cl
where not exists ( select 1 from table2 b
                   where b.customerid = cl.customerid
                   and b.id = a.id
                  )
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement