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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Outlying records between two tables

Author  Topic 

ldrenning
Starting Member

23 Posts

Posted - 2006-11-15 : 12:58:22
I have two tables that have a common column (ID). Now, what i am trying to do is find what is not in one table that is in the other.

For instance:

Table A
ID NAME
1 Tom
2 George
3 Richard

Table B
ID NAME
1 Tom
3 Richard
4 Kevin

With this information, I am trying to write a query that would tell me that Kevin is the only record that doesn't exist in both tables ... like an outlier.

I have tried using something like the following:

SELECT distinct id, name
FROM Table 1 INNER JOIN Table 2
ON Table 1.id <> Table 2.id

Any help would be great. Thanks!

-L

X002548
Not Just a Number

15586 Posts

Posted - 2006-11-15 : 13:05:32
quote:
Originally posted by ldrenning
I am trying to write a query that would tell me that Kevin is the only record that doesn't exist in both tables ... like an outlier.



But Kevin does exist in TableB

SELECT * FROM TableB LEFT JOIN TablA ON a.[id] = b.[id]
WHERE a.[id] IS NULL



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

ldrenning
Starting Member

23 Posts

Posted - 2006-11-15 : 13:14:05
Thanks for such a quick reply. I think you got what i was trying to achieve.

Much appreciated.

-L
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-11-15 : 13:44:16
What about George? He also is stored only in one table...
-- prepare test data
declare @TableA table (ID int, NAME varchar(10))

insert @tablea
select 1, 'Tom' union all
select 2, 'George' union all
select 3, 'Richard'

declare @TableB table (ID int, NAME varchar(10))

insert @tableb
select 1, 'Tom' union all
select 3, 'Richard' union all
select 4, 'Kevin'

-- find any single name
select isnull(a.id, b.id) [id],
isnull(a.name, b.name) [name]
from @tablea a
full join @tableb b on b.name = a.name
where a.id is null
or b.id is null

-- find any single name
select id,
[name]
from (
select id,
name
from @tablea
union all
select id,
name
from @tableb
) q
group by id,
[name]
having count(*) = 1


Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -