Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am using SQL server 2008. I have 3 tables. Table a has 1 column aid, table b has 1 column bid and table c has 2 columns aid, bid. Is it possible to use one SQL statement that returns all the combination of aid and bid that does NOT exists in table c.

e.g. table a has 2 rows: a, b
table b has 3 rows 1,2,3
table c has 2 rows (a, 2), (b,1)

and I want to return record set to be 4 rows: (a,1), (a,3), (b,2), (b,3)

Thanks in advance for any help.

Cathy
Posted

You can produce table a and b cartesian product and then subtract the c set from it to see the result. For subtraction use except operator. for more study read set functions of TSQL :
http://technet.microsoft.com/en-us/library/ms188055.aspx[^]

So your SQL is this :
SQL
select aid, bid from a,b as cartesian
except
select aid, bid from c


Good Luck
 
Share this answer
 
Comments
snoopy18 1-Dec-13 2:08am    
Thank you! It works perfectly.
Amir Mahfoozi 1-Dec-13 2:10am    
You're welcome.
Sure, what comes to mind is using a Common Table Expression to form a set of all the relationships and then Outer Join that with table C and form a set of the elements in the CTE that are not in C.
 
Share this answer
 
Comments
snoopy18 1-Dec-13 1:59am    
Thank you very much. This definitely helps and I will research on how to use CTE. However, I am looking for using one sql statement. Is it possible? Thanks.

Cathy
PIEBALDconsult 1-Dec-13 10:24am    
It would be one statement.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900