我的请求与此处描述的请求类似:sql server - join 2 tables based on earliest date in 2nd table
一个区别是我需要在第一张表中的出院日期之后找到门诊诊所就诊的最早可用日期,并且该日期在出院日期后的30天内。我想返回Nulls,在这段时间内没有跟进访问。
表1'排放' - 包含列:ClientId,DischargeFrom,Discharge Date
ClientId DischargeFrom DischargeDate
1 Unit A 2009/11/08
1 Unit A 2010/01/05
2 Unit A 2010/01/08
3 Unit B 2010/10/01
4 Unit A 2010/02/04
4 Unit B 2010/04/05
5 Unit A 2010/01/04
表2'OutpatientVisits - 包含列:ClientId,FollowUpClinicName,FollowUpVisitDt
ClientId FollowUpClinicName FollowUpVisitDt
1 Outpatient_Clinic_1 2009/05/04
1 Outpatient_Clinic_1 2009/07/07
1 Outpatient_Clinic_1 2010/01/14
1 Outpatient_Clinic_1 2010/01/18
2 Outpatient_Clinic_2 2007/11/05
2 Outpatient_Clinic_3 2009/12/22
2 Outpatient_Clinic_1 2010/01/04
5 Outpatient_Clinic_2 2010/01/01
5 Outpatient_Clinic_1 2010/01/11
7 Outpatient_Clinic_3 2010/01/25
一个ClientId可以有多个Discharges(这里是ClientIds 1和4),一个ClientId也可以与许多FollowUp Visits(ClientIds 1,2和5)相关联。我想在出院日期或之后返回第一个FollowUpVisitDt,但在出院日期后的30天内。我还希望退回那些没有后续访问的出院记录。
我尝试了以下语法,但我似乎无法返回最早的记录访问(请参阅ClientId 1在同一个出院日期有2个重复结果)。 ClientId 2也已解除,但未在结果中列出。
SELECT DISTINCT Discharges.ClientId,
Discharges.DischargeFrom,
Discharges.DischargeDate,
FollowUpVisits.FollowUpVisitDate,
DateDiff(DAY,Discharges.DischargeDate,FollowUpVisits.FollowUpVisitDate) As DaysBetween,
FollowUpVisits.rn
FROM Discharges LEFT JOIN
(
SELECT *, ROW_NUMBER() OVER (PARTITION By ClientId, FollowUpClinicName ORDER BY FollowUpVisitDate ASC) as rn
FROM [MH].[dbo].OutpatientVisits
) As FollowUpVisits
ON Discharges.ClientId=FollowUpVisits.ClientId
WHERE (FollowUpVisits.FollowUpVisitDate>=Discharges.DischargeDate and FollowUpVisitDate<=DATEADD(day,30,DischargeDate)) OR FollowUpVisits.FollowUpVisitDate Is Null
结果:
ClientId DischargeFrom DischargeDate FollowUpVisitDate DaysBetween rn
1 Unit A 2009-11-08 2009-12-27 49 3
1 Unit A 2009-11-08 2010-01-18 71 4
1 Unit A 2010-01-05 2010-01-18 13 4
3 Unit B 2010-10-01 NULL NULL NULL
4 Unit A 2010-02-04 NULL NULL NULL
4 Unit B 2010-04-05 NULL NULL NULL
5 Unit A 2010-01-04 2010-01-11 7 1
非常感谢您的帮助!我正在使用MSSQL 2005。
答案 0 :(得分:0)
尝试使用@blog_post = BlogPost.find(params[:id])
if @blog_post.update blog_post_params # fails because of validation
# save
else
object.errors.add(:date_assigned, "Your data is incorrect" + (@blog_post.date_assigned).to_s)
logger.debug "#{@blog_post.errors.get(:date_assigned)}" # Check your console, it will show you input from user.
flash.now[:error] = @blog_post.errors.full_messages.to_sentence
render :edit
end
:
outer apply