返回一行,来自两个不同表的两个不同列的最大日期

returning one row, with the max date from two different columns from two different tables

为 sql 服务器 08 R2 使用报表生成器 3.0。试图从 2 个不同表格的 2 个不同列中获取最新日期,但我得到 4 行而不是 1 行。在下图中,每个患者应该有一行。

我使用的脚本是这样的:

SELECT "Patient"."PatientID", "PatientLastName", "PatientFirstName", "DischargeDate", "PatVisitPayable"."ContactDate"
FROM "BTI"."Patient" 
JOIN "BTI"."PatAdmissions" ON "Patient"."PatientID" = "PatAdmissions"."PatientID" 
JOIN "BTI"."PatVisitPayable" ON "PatAdmissions"."PatientID" = "PatVisitPayable"."PatientID" 
JOIN "BTI"."PatAdmissionDivision" ON "PatAdmissions"."AdmissionID" = "PatAdmissionDivision"."AdmissionID"
GROUP BY "Patient"."PatientID", "PatientLastName", "PatientFirstName", "DischargeDate", "ContactDate"

我试过将 max(contactdate) 和 max(dischargedate) 放在 select 语句中,但仍然得到 4 行。不确定这是我应该在初始查询中包含的内容还是我可以在之后添加到报告中的内容。

4 rows for one patient

尝试从 GROUP BY 子句中删除 ContactDate 并在 SELECT 中使用 max() 函数:

SELECT pt.PatientID, 
       pt.PatientLastName, pt.PatientFirstName, pt.DischargeDate,                          
       MAX(ContactDate) as ContactDate
FROM BTI.Patient pt
JOIN BTI.PatAdmissions pa ON pt.PatientID = pa.PatientID
JOIN BTI.PatVisitPayable py ON pa.PatientID = py.PatientID 
JOIN BTI.PatAdmissionDivision pd ON pa.AdmissionID = pd.AdmissionID
GROUP BY pt.PatientID, pt.PatientLastName, 
         pt.PatientFirstName, pt.DischargeDate;

始终定义 table alise 以便 follow/read 和编写。 这假设 ContactDate 为 resonbale 格式。