Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
paul.rowling
Yak Posting Veteran
81 Posts |
Posted - 2003-03-12 : 07:06:53
|
| Hi,I have 3 tables (tablea, tableb, tablec) containing customer info. Each customer is identified in each table via a customer_id field. What I want to do is find which customers exist in all three tables, and then possibly which customers exist in tablea and tableb but not tablec.How can I achieve this? Is it possible to do it with one query?Any info would be greatly appreciated.CheersPaul |
|
|
paul.rowling
Yak Posting Veteran
81 Posts |
Posted - 2003-03-12 : 07:31:05
|
| I think I've found a way to do it! My query is as follows:select distinct customer_idfrom tableawhere customer_id in(select customer_idfrom tableb)and customer_id in(select customer_idfrom tablec)If I wanted to find those who are in two tables but not the other I would change the "and customer_id in" to "and customer_id not in".Does this look correct?CheersPaul |
 |
|
|
samsekar
Constraint Violating Yak Guru
437 Posts |
Posted - 2003-03-12 : 08:17:49
|
| I have taken some different scenario. HTH..use tempdbgocreate table A (x int)create table B (y int)create table C (z int)insert into A values (1)insert into B values (1)insert into C values (1)insert into A values (2)insert into B values (2)insert into A values (3)insert into A values (4)insert into B values (4)insert into C values (4)SELECT CASE A.x WHEN C.z THEN A.x ELSE NULL END AS 'ExistsIn3Tables', CASE A.x WHEN C.z THEN NULL ELSE A.x END AS 'ExistsInTablesA&B' FROM A INNER JOIN B ON A.x=B.y LEFT OUTER JOIN C ON A.x = C.z___________________________________________________________________________Success is not a destination that you ever reach. Success is the quality of your journey. |
 |
|
|
X002548
Not Just a Number
15586 Posts |
Posted - 2003-03-12 : 11:30:26
|
| This should give you everything you need. You can then evaluate the results however you want:CREATE TABLE Tablea (id int)GoCREATE TABLE Tableb (id int)GoCREATE TABLE Tablec (id int)GoInsert Into Tablea (id) Values (1)Insert Into Tableb (id) Values (1)Insert Into Tablec (id) Values (1)Insert Into Tablea (id) Values (2)Insert Into Tableb (id) Values (3)Insert Into Tablec (id) Values (4)Go SELECT * FROM Tablea aFULL OUTER JOIN Tableb b ON a.id = b.idFULL OUTER JOIN Tablec c ON b.id = c.idDROP TABLE TableaGoDROP TABLE TablebGoDROP TABLE TablecGoBrett8-) |
 |
|
|
paul.rowling
Yak Posting Veteran
81 Posts |
Posted - 2003-03-12 : 11:32:47
|
| Thanks alot, I'll give it a try!!CheersPaul |
 |
|
|
|
|
|