简体   繁体   English

在一行上显示来自同一个连接表的不同值

[英]Show different values from the same joined table on one row

There are two doctors (DOC_A and DOC_B) assigned to every patient.为每位患者分配了两名医生(DOC_A 和 DOC_B)。 There are 3 tables.有3张桌子。 The PATIENT table has the Patient_ID and DOC_A's DOC_ID. PATIENT 表具有 Patient_ID 和 DOC_A 的 DOC_ID。 The CONSULT table has Patient_ID and DOC_B's DOC_ID. CONSULT 表有 Patient_ID 和 DOC_B 的 DOC_ID。 Finally, the DOCTOR table has both DOC_A and DOC_B's DOC_ID with their FirstName and LastName.最后,DOCTOR 表同时具有 DOC_A 和 DOC_B 的 DOC_ID 及其 FirstName 和 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.我想在每一行上显示一个不同的 Patient_ID,其中包含 DOC_A 和 DOC_B 以及 FirstName 和 LastName(连接)而不是 DOC_ID。

Example Output (manually created):示例 Output(手动创建):

Patient_ID患者 ID DOC_A FirstLast DOC_A FirstLast DOC_B FirstLast DOC_B FirstLast
123 123 John Smith约翰·史密斯 Jane Smith简·史密斯
456 456 Nathaniel Hawkeye纳撒尼尔鹰眼 Cora Munroe科拉·门罗

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:如果您将 PATIENT 和 CONSULT 表视为 1 个表(因为它们共享一个 Patient_ID),那么想象与 DOCTOR 表的连接会更容易一些......您必须连接两次,只要您使用就可以了别名:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM