我有两张与医院活动有关的表格;第一个用PATIENT_ID和REFERRAL_DATE列出患者转诊,第二个用PATIENT_ID,DISCHARGE_DATE和DISCHARGE_LOCATION列出放电。每位患者可多次转诊和出院
我正在尝试运行一个查询,该查询将为每个推荐人提供后续出院日期和出院地点。
我已经做到这一点了(但是无法弄清楚如何使用聚合函数来为MIN(DISCHARGE_DATE)拉入DISCHARGE_LOCATION):
SELECT
Referral.PATIENT_ID,
Referral.REFERRAL_DATE,
MIN(Discharge.DISCHARGE_DATE) AS NEXT_DISCHARGE
FROM Referral
LEFT OUTER JOIN Discharge
ON Referral.PATIENT_ID = Discharge.PATIENT_ID
AND Discharge.DISCHARGE_DATE > Referral.REFERRAL_DATE
GROUP BY
Referral.PATIENT_ID,
Referral.REFERRAL_DATE
任何帮助都非常感谢!
表格示例:
Referral:
PATIENT_ID REFERRAL_DATE
Patient1 10/08/2012
Patient1 05/09/2012
. . .
Discharge:
PATIENT_ID DISCHARGE_DATE DISCHARGE_LOCATION
Patient1 01/08/2012 Hospital
Patient1 25/08/2012 Home
Patient1 15/09/2012 Care Home
. . .
我正在寻找的结果是:
PATIENT_ID REFERRAL_DATE NEXT_DISCHARGE DISCHARGE_LOCATION
Patient1 10/08/2012 25/08/2012 Home
Patient1 05/09/2012 15/09/2012 Care Home
. . .
答案 0 :(得分:1)
您可以将结果反馈到出院表,以获得理想的结果。
select
results.*,
discharge.DISCHARGE_LOCATION
from
(
SELECT
Referral.PATIENT_ID,
Referral.REFERRAL_DATE,
MIN(Discharge.DISCHARGE_DATE) AS NEXT_DISCHARGE
FROM Referral
LEFT OUTER JOIN Discharge
ON Referral.PATIENT_ID = Discharge.PATIENT_ID
AND Discharge.DISCHARGE_DATE > Referral.REFERRAL_DATE
GROUP BY
Referral.PATIENT_ID,
Referral.REFERRAL_DATE
) results
left join discharge
on results.NEXT_DISCHARGE = discharge.discharge_date
and results.patient_id = discharge.patient_id