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
 Comparing similar tables

Author  Topic 

kopfgeldjagar
Starting Member

14 Posts

Posted - 2009-04-04 : 06:34:32
Sorry about the dumb question, i'm VERY new to sql, so you guys may have to go rudimentary for me, but I need help writing query. I have two tables i am trying to compare to tables that have the same names with similar but different job titles. For instance (as csv) one table may have:

John,Smith,Engineer II

And the other table will have something like:

JOHN,SMITH,LVL II ENGINEER

It's a monthly employee audit I am trying to automate. is there a way to tell SQL 2005 to see engineer II as LVL II engineer? or vice versa? suggestions? the second step would be to compare the two tables to see if John Smith is in one table without being in the other and vice versa.
I was using a union all statment like:

select last, first, title from employees
except
select last, first, title from roster
union all
select last, first, title from roster,
except
select last, first, title from employees

But with this query I only get what is different in one table. Any help is much appreciated. Again sorry about the dumb questions, but our SQL guru quit, and I got thrown into the job!

Thanks!

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2009-04-04 : 09:10:53
this could get you started. There is a lot of ways to accomplish these steps, here's one:

--This will show where only one table has the person (as comparing exact match on first and last name)

select min([srcTable]) as srcTable
,[last]
,[first]
,min(title) as title
from (
select 'roster' as [srcTable], [last], [first], title from roster
union all
select 'employees' as [srcTable], [last], [first], title from employees
) d
group by [last]
,[first]
having count(*) = 1 --limit restuls to where only one row exists from both tables


--This shows where the person exists in both table with different titles
select e.[last]
e.[first]
e.title as emloyee_Title
r.title as roster_Title
from employees e
inner join roster r
on r.[last] = e.[last]
and r.[first] = e.[first]
where isNull(r.title,'no Title') != isNull(e.title, 'no Title')


EDIT:
a more difficult problem you may have is when there are variations of the names like "jon" vs. "Jonathon", or "William" vs. "Bill", or "John A." vs. "John".

Be One with the Optimizer
TG
Go to Top of Page

kopfgeldjagar
Starting Member

14 Posts

Posted - 2009-04-05 : 09:34:05
thanks, i'll try it today.
Go to Top of Page

kopfgeldjagar
Starting Member

14 Posts

Posted - 2009-04-06 : 11:52:36
That worked. Thank you!
Go to Top of Page
   

- Advertisement -