I have a list of users in a database table called Users (SQL Server 2008 R2). In addition to the user’s UserName, there are two fields that classify the user – for simplicity we’ll say Department and JobTitle.
| UserName | Department | JobTitle |
------------------------------------------
| Joe | IT | SysAdmin |
| Jim | IT | DBA |
| Jeff | Sales | SalesMgr |
| Mack | Sales | Rep |
I also have a table, ActiveJobs, that lists certain combinations of Department and JobTitle that I actually care about.
| Department | JobTitle |
-----------------------------
| IT | SysAdmin |
| Sales | SalesMgr |
| Sales | Rep |
I want to select each of the records from Users that matches the combination of Department / JobTitle in ActiveJobs. I thought this query would do it:
SELECT Users.*
FROM Users
INNER JOIN ActiveJobs DEP
ON Users.Department = DEP.Department
INNER JOIN ActiveJobs JOB
ON Users.JobTitle = JOB.JobTitle
But that returns the same User record more than once in many cases (which I think is caused by the duplicates in the Department column – but I don’t really understand why). For the example above, I’m getting (Joe, Joe, Jim, Mack) even though I was hoping to just get (Joe, Jim, Mack).
What query would get the subset of User records that has a matching combination of Department and JobTitle in Active Jobs?
Put an “AND” in your join clause instead of joining twice.