sql – 获取行中日期值之前的最新日期

我正在使用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的2/1/13和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;

Example On SQL Fiddle

点赞