我正在使用MSSQL 2008 R2。我正在尝试获取最新数据日期,直到存储在另一列中的日期为止。我可以在子查询中使用max(ProcedureDate)整体拉取最新的数据日期;但是,我需要存储在该列中的日期之前的最新日期。
这是一个例子:
Current Table: Procedures ID Patient ProcedureType ProcedureDate 1 George ExamA 1/1/2013 2 George TreatmentA 1/3/2013 2 George TreatmentB 1/5/2003 4 George ExamB 2/1/2013 5 George TreatmentA 2/5/2013 Desired Table: ProceduresWithLastExam ID Patient ProcedureType ProcedureDate LastExamDate DaysSinceLastExam LastExamType 1 George ExamA 1/1/2013 1/1/2013 0 ExamA 2 George TreatmentA 1/3/2013 1/1/2013 2 ExamA 3 George TreatmentB 1/5/2013 1/1/2013 4 ExamA 4 George ExamB 2/1/2013 2/1/2013 0 ExamB 5 George TreatmentA 2/5/2013 2/1/2013 4 ExamB
我尝试使用以下内容,但它仅拉回该患者的最新数据日期。
select p.*, a.LastExamDate, a.ProcedureType as LastExamType from Procedures p left join ( select exams.Patient, exams.ProcedureType, MAX(exams.ProcedureDate) as LastExamDate from Procedures exams where ProcedureType like 'Exam%' group by exams.Patient, exams.ProcedureType )a on p.Patient = a.Patient
所有行的结果均为LastExamDate,是13/1/13,ExamB是LastExamType,是ExamB。
我试图在我的左联接,where子句和子查询中包括一些其他日期参数,但均未成功。
请注意,我省略了datediff逻辑,直到我得到正确的日期才能返回。
在此先感谢您的帮助。
您可以使用OUTER APPLY。它就像一个相关的子查询,但是允许多个列:
SELECT p.ID, p.Patient, p.ProcedureType, p.ProcedureDate, [LastExamDate] = exam.ProcedureDate, [DaysSinceLastExam] = DATEDIFF(DAY, exam.ProcedureDate, p.ProcedureDate), [LastExamType] = exam.ProcedureType FROM Procedures p OUTER APPLY ( SELECT TOP 1 exams.ProcedureType, exams.ProcedureDate FROM Procedures exams WHERE Exams.ProcedureType LIKE '%Exam%' AND Exams.Patient = p.Patient AND Exams.ProcedureDate <= p.ProcedureDate ORDER BY Exams.ProcedureDate DESC ) exam;