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

时间:2018-04-30 14:19:46

标签: sql ssrs-2008 reportbuilder3.0

对sql server 08 R2使用report builder 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"

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

4 rows for one patient

1 个答案:

答案 0 :(得分:0)

尝试从ContactDate子句中删除GROUP BY并使用max()中的SELECT功能:

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;

始终定义表 alise ,可以很容易地跟踪/读取和写入。 这假设ContactDate为共鸣格式。