【问题标题】:Joining multiple tables with same identifier & pulling in a field based on shared identifier加入具有相同标识符的多个表并基于共享标识符拉入一个字段
【发布时间】:2018-06-08 02:18:14
【问题描述】:

上下文:一家医疗保健诊所有 2 张表格:一张是关于患者就诊的,另一张是关于患者预约的。它们不是 1:1;可以不预约就预约,也可以不预约就预约。两个表的标识符都是遭遇 ID,enc_ID。我正在尝试将这些表外部连接在一起并提取患者姓名。

访问表(V)的简化示例:

enc_ID         Visit_date     Patient_ID
1              2018-06-01     10
2              2018-06-02     11

还有约会数据(A):

enc_ID         Appointment_time          Patient_ID
1              2018-06-01 13:00          10
3              2018-06-03 14:00          12

在 visit_ID 上将这些外连接会产生类似的结果:

enc_ID      V.Visit_date   A.Appointment_time   V.Patient_ID   A.Patient_ID
1           2018-06-01     2018-06-01 13:00     10             10
2           2018-06-02     NULL                 11             NULL
3           NULL           2018-06-03 14:00     NULL           12

假设我想基本上结合 V.Patient_ID 和 A.Patient_ID,并从另一个表 (P) 中提取患者姓名,加入 Patient_ID。所需的输出:

enc_ID      V.Visit_date   A.Appointment_time   Patient_ID   Patient_Name
1           2018-06-01     2018-06-01 13:00     10           Patient A
2           2018-06-02     NULL                 11           Patient B
3           NULL           2018-06-03 14:00     13           Patient C

这如何实现?我可能遗漏了一些明显的东西,但我不知道如何加入 P.Patient_Name 而不必将其加入 V.Patient_ID 或 A.Patient_ID,这两者都会导致患者姓名为空。

提前致谢!

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    只要两个表中的 enc_ID 都不能为空,您就可以将这些字段与 COALESCE 组合起来:

    SELECT 
        COALESCE(V.Patient_ID, A.Patient_ID) AS enc_ID,
        V.Visit_date,
        A.Appointment_time,
        COALESCE(V.Patient_ID, A.Patient_ID) AS Patient_ID,
        P.Patient_Name
    FROM V 
    FULL JOIN A ON V.enc_ID = A.enc_ID
    INNER JOIN P 
        ON P.Patient_ID = V.Patient_ID
        OR P.Patient_ID = A.Patient_ID
        -- ON P.Patient_ID = COALESCE(V.Patient_ID, A.Patient_ID) also works
    

    【讨论】:

      【解决方案2】:

      您可以使用ISNULL 加入表P。

      ...(Your outer join query)
      LEFT JOIN P
      ON P.Patient_ID = ISNULL(V.Patient_ID, A.PatientID)
      

      【讨论】:

        猜你喜欢
        • 2020-12-04
        • 2019-12-02
        • 2011-04-28
        • 2018-03-13
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 2015-05-27
        • 1970-01-01
        相关资源
        最近更新 更多