4

我正在使用 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

所有行的结果都是 2/1/13 作为 LastExamDate 和 ExamB 作为 LastExamType。

我尝试在左连接、where 子句和子查询中包含一些额外的日期参数,但没有成功。

请注意,我已经省略了 datediff 逻辑,直到我可以得到正确的返回日期。

在此先感谢您的帮助。

4

2 回答 2

1

您可以使用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;

SQL Fiddle 示例

于 2013-02-15T13:40:02.753 回答
1

这可以通过以下方式完成OUTER APPLY

SELECT  A.*, 
        B.ProcedureDate LastExamDate, 
        DATEDIFF(DAY,B.ProcedureDate,A.ProcedureDate) DaysSinceLastExam,
        B.ProcedureType
FROM Procedures A
OUTER APPLY (   SELECT TOP 1 *
                FROM Procedures
                WHERE Patient = A.Patient 
                AND ProcedureDate <= A.ProcedureDate
                AND ProcedureType LIKE 'Exam%'
                ORDER BY ProcedureDate DESC) B

这是一个演示供您尝试。

于 2013-02-15T13:41:23.853 回答