1

I'm not sure exactly how to get this.

What I have is something like this.

TableA:  VisitID, PersonID1, PersonID2
TableB:  PersonID, FirstName, LastName

I'd like to return Visit ID, name of PersonID1, name of personID2.

Usually I would just do a simple join, but I can't seem to get that to work

It should go something like

SELECT A.VisitID, B.FirstName+B.LastName, B.FirstName+B.LastName (this is dup, wont work)
FROM TableA A
JOIN TableB B ON TableA.PersonID1=TableB.PersonID OR TableA.PersonID2=TableB.PersonID

Thanks!

4 Answers 4

4
select A.VisitID, B1.FirstName+B1.LastName, B2.FirstName+B2.LastName
from TableA A
    join TableB B1 on A.PersonID1 = B1.PersonId
    join TableB B2 on A.PersonID2 = B2.PersonId

essentially, you join with TableB twice, once per foreign key in TableA

Sign up to request clarification or add additional context in comments.

Comments

3

You have to join tableb twice, once for each id:

select VisitID, b1.FirstName, b1.LastName, b2.FirstName, b2.LastName
from TableA
        inner join TableB b1 on TableA.PersonID1=b1.PersonID
        inner join TableB b2 on TableA.PersonID2=b2.PersonID

1 Comment

This works great (as do the other answers), Thanks very much!
2

I think simple inner join two times should do the trick.

select A.VisitID, (BB.FirstName + ' ' + BB.LastName) as Person1, 
(BC.FirstName + ' ' + BC.LastName) as Person2
from TableA A
inner join TableB BB on A.PersonID1 = BB.PersonId
inner join TableB BC on A.PersonID2 = BC.PersonId

Comments

1

If PersonID1/PersonID2 are nullable, the join has to be left join

Select
      A.VisitID
    , B1.FirstName + ' ' + B1.LastName
    , B2.FirstName + ' ' + B2.LastName
From
    TableA A
Left Join
    TableB B1
On
    A.PersonID1 = B1.PersonID
Left Join
    TableB B2
On
    A.PersonID1 = B2.PersonID

1 Comment

Yes but if personid1/2 are nullable, then maybe this approach isn't the best anyway. An ID linking to a list of person ID's would be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.