如何在sql中从当前日期中检索最近的过去日期,从当前日期检索最近的未来日期



我正在开发一个记录患者预约就诊的小型应用程序。我有一个Patient表和Appointment表。

在Appointment表中,我有以下字段:AppointmentIdAppointmentDatePatientId

在患者表中,我有PatientIdPatientName

Appointment表中,我有如下记录:

1 | 2020-08-08 | 2
2 | 2020-10-11 | 2
3 | 2020-12-15 | 2
4 | 2020-12-24 | 2

我想检索的是,对于所有患者,我获取PatientId的数据集。如果我今天运行查询,我想检索上次约会日期,即2020-10-11和下一次约会日期,如2020-12-15

我尝试了以下方法,但没有得到想要的结果。有人能帮我处理这个SQL查询吗?

SELECT 
patient.PatientName,
MAX(appointment.AppointmentDate) AS NextVisit,
MIN(appointment.AppointmentDate) AS LastVisit
FROM 
Patient patient 
INNER JOIN 
Appointment appointment ON patient.PatientId = appointment.PatientId

您可以在sql中使用left joins,如下所示:

Select p.patientid, patientname,
Max(ap.appointmentdate) as previous_appointment,
Min(an.appointmentdate) as next _appointment
from patient p
Left join appointment ap on p.patientid = ap.patientid and ap.appointmentdate < sysdate
Left join appointment an on p.patientid = an.patientid and an.appointmentdate > sysdate
Group by p.patientid, p.patientname

您也可以按如下方式使用conditional aggregation

Select p.patientid, patientname,
Max(case when ap.appointmentdate < sysdate then ap.appointmentdate end) as previous_appointment,
Min(case when ap.appointmentdate > sysdate then ap.appointmentdate end) as next _appointment
from patient p
Left join appointment ap on p.patientid = ap.patientid
Group by p.patientid, p.patientname

请根据您的要求使用>=<=,而不是<>

最新更新