如何排序和选择每条记录的最新日期

时间:2013-08-12 15:23:39

标签: sql

我想抓住以下内容:

上次访问日期(Eventdate)有实验室访问地点的患者列表。我需要提取过去3个月的数据。 以下查询运行正常,但是当我做一些QA时,我发现对于一些出现LAB的患者来说,这不是他们的最后一次访问。我的查询出了什么问题?

感谢您的帮助。

SELECT
SSKeyField=Event_AntiCoag.SS_Event_AntiCoag_ID, 
SSParentField=A.SS_Patient_ID, 
A.Last_Name, 
A.First_Name, 
A.Patient_ID, 
A.MaxOfEventDate, 
A.VisitLoc,
A.Active

FROM 
(SELECT Demographics.Last_Name, Demographics.First_Name
, Demographics.SS_Patient_ID, Demographics.Patient_ID
, Max(Event_AntiCoag.EventDate) AS MaxOfEventDate
, AntiCoag_Extension.VisitLoc
, Demographics_Extension.Active

FROM ((Event_AntiCoag INNER JOIN Demographics ON Event_AntiCoag.SS_Patient_ID = Demographics.SS_Patient_ID) INNER JOIN AntiCoag_Extension ON Event_AntiCoag.SS_Event_AntiCoag_ID = AntiCoag_Extension.SS_Event_AntiCoag_ID) INNER JOIN Demographics_Extension ON Event_AntiCoag.SS_Patient_ID = Demographics_Extension.SS_Patient_ID

GROUP BY Demographics.Last_Name, Demographics.First_Name, Demographics.SS_Patient_ID
, Demographics.Patient_ID, AntiCoag_Extension.VisitLoc, Demographics_Extension.Active
)A 

INNER JOIN (Event_AntiCoag INNER JOIN AntiCoag_Extension 
ON Event_AntiCoag.SS_Event_AntiCoag_ID = AntiCoag_Extension.SS_Event_AntiCoag_ID) 
ON (A.MaxOfEventDate = Event_AntiCoag.EventDate) 
      AND (A.SS_Patient_ID = Event_AntiCoag.SS_Patient_ID)

WHERE A.Active=1 
     AND ((A.VisitLoc='Lab') AND (A.MaxOfEventDate >= '4/1/2013')) 
    ORDER BY A.Last_Name, A.First_Name

0 个答案:

没有答案