将行映射到不同表中的列

时间:2016-07-19 13:36:15

标签: sql oracle plsql

我很难过如何优雅地将数据从行映射到其他表中的列。

输入表格

FORM_SUBMISSION表 -

ID =表单标识符 ENTRY_ID =问题标识符 RESPONSE =他们的回应

ID  ENTRY_ID   RESPONSE
4   24         John 
4   25         Doe
4   26         Male
4   32         NY
4   30         Life-Threatening
4   30         Other Serious
4   30         Hospitalization
4   28         Tylenol
4   31         I have a headache.

我需要将其映射到几个表PATIENT_INFOPATIENT_OUTCOME

输出表

PATIENT_INFO

REPORT_ID    FIRST_NAME   LAST_NAME    STATE   GENDER    COMPLAINT
4            John         Doe          NY      Male      I have a headache.

PATIENT_OUTCOME

REPORT_ID    OTHER_SERIOUS_IND   LIFE_THREAT_IND    HOSPITAL_IND   DISABILITY_IND
4            Y                   Y                  Y              N

所以没有直接的方法将行链接到列, 是否可以基于ENTRY_ID和列名创建映射?虽然我知道IND列的所有行都基于ENTRY_ID = 30。

1 个答案:

答案 0 :(得分:1)

可以使用条件聚合。但是,最后,您仍然需要找出正确执行映射的规则。

这是一些基于我对映射如何工作的基本理解的示例SQL。你可能需要进一步调整它。

<强> PATIENT_INFO

select id as report_id,
       max(case when entry_id = 24 then response end) as first_name,
       max(case when entry_id = 25 then response end) as last_name,
       max(case when entry_id = 32 then response end) as state,
       max(case when entry_id = 26 then response end) as gender,
       max(case when entry_id = 31 then response end) as complaint
  from form_submission
 group by id

<强> PATIENT_OUTCOME

select id as report_id,
       nvl(max(case when entry_id = 30 and response = 'Other Serious' then 'Y' end), 'N') as OTHER_SERIOUS_IND,
       nvl(max(case when entry_id = 30 and response = 'Life-Threatening' then 'Y' end), 'N') as LIFE_THREAT_IND,
       nvl(max(case when entry_id = 30 and response = 'Hospitalization' then 'Y' end), 'N') as HOSPITAL_IND,
       nvl(max(case when entry_id = 30 and response = '??Disability??' then 'Y' end), 'N') as DISABILITY_IND
  from form_submission
 group by id