Friday, May 3, 2013

[SQL Server] Comparing 2 Tables, Joins with Specific Data

[SQL Server] Comparing 2 Tables, Joins with Specific Data


Comparing 2 Tables, Joins with Specific Data

Posted: 02 May 2013 06:55 PM PDT

I currently have tables that'd like to compare the differences between. They have the exact same column and uses. The problem that I run into is not only am I comparing from separate tables, they're separate databases and both tables use different IDs for the user (original design that I inherited). I can get around this by using joins to link the IDs because "users_hierarchy" has the old user id in it's tables, but I'm literally stumped on how to get them to do a differential.Essentially, I want to do two queries, one each to grab the differences between the two tables.Below is an example of what I'm referring to, I'm looking to have one query return 2 and the other 4, my real tables have actual employeeids and skill numbers. So I have multiple records of employeeid and different skill IDs.The other issue is that the differential should ignore employees that are not in the hierarchy table, so I'd need it to ignore 99999 since it isn't in the hierarchy table. This is because the old table is has users who aren't part of my department and I'd like to not include them in my query.[code="sql"]CREATE TABLE [dbo].[old_skills]( [id] [int] NOT NULL, [skillid] [int] NOT NULL) ON [PRIMARY]CREATE TABLE [dbo].[users_hierarchy]( [employeeid] [int] NOT NULL, [skillid] [int] NOT NULL) ON [PRIMARY]CREATE TABLE [dbo].[new_skills]( [id] [int] NOT NULL, [skillid] [int] NOT NULL) ON [PRIMARY]INSERT INTO [dbo].[users_hierarchy] ([employeeid] ,[oldid]) VALUES (12345 ,67890)GOINSERT INTO [dbo].[new_skills] ([id] ,[skillid]) VALUES (12345 ,1)GOINSERT INTO [dbo].[new_skills] ([id] ,[skillid]) VALUES (12345 ,4)GOINSERT INTO [dbo].[old_skills] ([id] ,[skillid]) VALUES (67890 ,2)GOINSERT INTO [dbo].[old_skills] ([id] ,[skillid]) VALUES (67890 ,1)GOINSERT INTO [dbo].[old_skills] ([id] ,[skillid]) VALUES (99999 ,2)GO[/code]I think you'd use something like this? [code="sql"]SELECT users.employeeid, skill.skillidFROM dbo.users_hierarchy as 'users' INNER JOIN dbo.old_skills as skill ON skill.id = users.employeeidWHERE NOT EXISTS (SELECT 1 FROM dbo.new_skills as skill where skill.id = users.oldid)[/code]Any help is appreciated!

No comments:

Post a Comment

Search This Blog