我正在使用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逻辑,直到我能够获得正确的日期返回。
提前感谢您的帮助。
答案 0 :(得分: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;
<强> Example On SQL Fiddle 强>
答案 1 :(得分: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
以下是demo供您试用。