我正在开发一个记录患者预约就诊的小型应用程序。我有一个Patient
表和Appointment
表。
在Appointment表中,我有以下字段:AppointmentId
、AppointmentDate
、PatientId
在患者表中,我有PatientId
、PatientName
在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
请根据您的要求使用>=
或<=
,而不是<
和>
。