I have a SQL table that I cannot change the structure of.
The table Employee_Team has 5 columns: TeamID, Employee1, Employee2, Employee3 and Employee4. The fields of columns Employee1, Employee2, Employee3 and Employee4 contain an EmployeeID. Each Employee ID has a City in the table Employee. It’s possible to have multiple employees on the same row of Employee_Team that are living in the same town. There will always be at least 1 employee that will live in the town I’m looking for.
example http://www.atriasoft.com/table.png
Example:
I want the first employee that lives in New York. In the case of TeamID 01, it will be Employee2 (I don’t want Employee 4 even though his city is New York) and for the case of TeamID 02, it will be Employee1 (I still don’t want the second employee that lives in New York).
I currently have a code that gives me every employee that lives in New York:
SELECT *
FROM Employee_Team
INNER JOIN Employees
ON Employees.EmployeeID = Employee_Team.Employee1 OR
Employees.EmployeeID = Employee_Team.Employee2 OR
Employees.EmployeeID = Employee_Team.Employee3 OR
Employees.EmployeeID = Employee_Team.Employee4
WHERE Employees.City = ‘New York’
What I am looking for is a code that takes only the first employee living in New York.
Any hints will be much appreciated!
You actually can safely “change” the definition of your table, virtually, by using it as the basis of a view:
Now, NormalTeams will let you SELECT the data the way you expect to be able to:
will give you the first team member “number” for New York.
will give you the more general solution for every City / Team combination.
You can join these results back to NormalTeams to get the employee ID.