There are two doctors (DOC_A and DOC_B) assigned to every patient. There are 3 tables. The PATIENT table has the Patient_ID and DOC_A's DOC_ID. The CONSULT table has Patient_ID and DOC_B's DOC_ID. Finally, the DOCTOR table has both DOC_A and DOC_B's DOC_ID with their FirstName and LastName.
I'd like to show a distinct Patient_ID on each row with both DOC_A and DOC_B with FirstName and LastName (concatenated) instead of DOC_ID's.
Example Output (manually created):
| Patient_ID | DOC_A FirstLast | DOC_B FirstLast |
|---|---|---|
| 123 | John Smith | Jane Smith |
| 456 | Nathaniel Hawkeye | Cora Munroe |
CodePudding user response:
If you think about the PATIENT and CONSULT table as being 1 table (because they share a Patient_ID), it gets a little easier to imagine the joins to the DOCTOR table... you have to join twice which is fine as long as you use an alias:
select p.patient_id
, concat(doca.firstname,' ',doca.lastname) as DOC_A_FirstLast
, concat(docb.firstname,' ',docb.lastname) as DOC_B_FirstLast
from dbo.PATIENT p
join dbo.CONSULT c
on c.patient_id = p.patient_id
join dbo.DOCTOR doca
on doca.doc_id = p.doc_id
join dbo.DOCTOR docb
on docb.doc_id = c.doc_id;
