[英]In SQL, how to join multiple foreign keys IDs in multiple columns of a table to a single primary key in another table and uniquely select one?
Table A: Patient Encounters With Linked Diagnoses(DX)表 A:患者遇到的相关诊断(DX)
Encounter_ID Encounter_ID | Date日期 | Primary_DX Primary_DX | DX_2 DX_2 | DX_3 DX_3 | DX_4 DX_4 |
---|---|---|---|---|---|
11111 11111 | 01/01/2020 2020 年 1 月 1 日 | 234234 234234 | 256756 256756 | 254537 254537 | 678688 678688 |
11112 11112 | 05/01/2020 2020 年 5 月 1 日 | 344564 344564 | 234553 234553 | 6786667 6786667 | 234234 234234 |
11113 11113 | 01/01/2022 2022 年 1 月 1 日 | 123233 123233 | 656444 656444 | 678688 678688 | 535465 535465 |
11114 11114 | 01/01/2021 2021 年 1 月 1 日 | 435345 435345 | 666654 666654 | 3453453 3453453 | 456448 456448 |
Table B : Diagnoses(DX) Code Linked with Their respective ICD Code表 B :诊断 (DX) 代码与其各自的 ICD 代码相关联
NOTE: The codes for this table is filtered for DX_ID
/ ICD_CODE
's specifically for heart disease.注意:此表的代码已针对DX_ID
/ ICD_CODE
进行过滤,专门针对心脏病。
DX_ID DX_ID | ICD_CODE ICD_CODE |
---|---|
234234 234234 | N123.42 N123.42 |
344564 344564 | N45.32 N45.32 |
234553 234553 | N153.24 N153.24 |
678688 678688 | N365.34 N365.34 |
I seek to get only the encounters with the following condition:我寻求只遇到以下条件:
At least one of the Primary_DX, DX_2,DX_3,DX_4 codes in Table A is a heart disease, that is, their respective diagnosis code can be linked to table B.表A中的Primary_DX、DX_2、DX_3、DX_4代码中至少有一个是心脏病,即它们各自的诊断代码可以链接到表B。
From this list, I seek to only get the ICD_Code for only that heart disease diagnosis code .从这个列表中,我试图只获取该心脏病诊断代码的 ICD_Code 。
I have to do this in two steps:我必须分两步执行此操作:
Get all encounters where at least one of the DX_code
in Table A is a DX_Code
in Table B.获取表 A 中至少一个DX_code
是表 B 中的DX_Code
的所有遭遇。
From this temporary table, select only the heart disease code and retrieve the ICD_code
.从这个临时表中, select 只有心脏病代码并检索ICD_code
。 If there are multiple heart disease for a single encounter, then they will show up as two separate rows.如果一次遭遇有多种心脏病,那么它们将显示为两个单独的行。
So final output could have the following format:所以最终的 output 可以具有以下格式:
Encounter_ID Encounter_ID | ICD_CODE ICD_CODE |
---|---|
11111 11111 | N123.42 N123.42 |
11111 11111 | N45.32 N45.32 |
11112 11112 | N123.42 N123.42 |
11115 11115 | N15.42 N15.42 |
11114 11114 | N123.42 N123.42 |
Now filter for heart disease dx_codes with the EXISTS
cause as below:现在过滤具有EXISTS
原因的心脏病 dx_codes,如下所示:
SELECT
Enounter_ID,
Primary_DX,
DX_2,
DX_3,
DX_4,
FROM
TABLE_A
WHERE
EXISTS (SELECT 1 FROM TABLE_B)
But I am getting encounters where NONE of the linked diagnoses are from the heart disease table.但是我遇到了没有任何关联诊断来自心脏病表的情况。
Wouldn't this be enough?这还不够吗?
select Encounter_ID, ICD_CODE
from Table_A, Table_B
where Primary_DX = DX_ID
or DX_2 = DX_ID
or DX_3 = DX_ID
or DX_4 = DX_ID
order by Encounter_ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.