我的查询未返回结果

时间:2015-09-17 18:03:25

标签: sql

我对SQL非常新,有点沮丧。我确信我的查询写错了,因为它不会返回任何结果。我需要确定14到19岁之间有多少人在过去两年内在特定学校进行了体检。我的查询如下:

SELECT      PatientProfile.Last, 
            PatientProfile.First, 
            PatientProfile.City,     
            PatientProfile.Birthdate, 
            PatientProfile.SchoolName, 
            Appointments.ApptStart, 
            ORDERCODES.CODE, 
            DoctorFacility.PlaceOfServiceMId
FROM        PatientProfile 
INNER JOIN  ORDERS          ON  PatientProfile.PId = ORDERS.PID 
INNER JOIN  ORDERCODES      ON  ORDERS.ORDCODEID = ORDERCODES.ORDCODEID         
INNER JOIN  DoctorFacility  ON  PatientProfile.DoctorId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.FacilityId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.PrimaryCareDoctorId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.RefDoctorId = DoctorFacility.DoctorFacilityId 
INNER JOIN  Appointments    ON  DoctorFacility.DoctorFacilityId = Appointments.DoctorId 
                                AND DoctorFacility.DoctorFacilityId = Appointments.FacilityId 
                                AND DoctorFacility.DoctorFacilityId = Appointments.ResourceId
WHERE   (PatientProfile.Birthdate BETWEEN CONVERT(DATETIME, '2001-09-01 00:00:00', 102) AND CONVERT(DATETIME, '2005-09-01 00:00:00', 102)) 
AND     (Appointments.ApptStart > CONVERT(DATETIME, '2013-09-01 00:00:00', 102)) 
OR      (PatientProfile.City = 'Salem') 
OR      (PatientProfile.City = 'Peabody')
ORDER BY PatientProfile.Last, PatientProfile.City

我的查询运行没有错误,但我没有得到任何结果。也许其中一个连接是错误的。我很感激你提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

我不知道你的桌面结构,所以我无法解决你的问题,但这完全错误地突然出现在我身上:

INNER JOIN  DoctorFacility  ON  PatientProfile.DoctorId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.FacilityId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.PrimaryCareDoctorId = DoctorFacility.DoctorFacilityId 
                                AND PatientProfile.RefDoctorId = DoctorFacility.DoctorFacilityId     
INNER JOIN  Appointments    ON  DoctorFacility.DoctorFacilityId = Appointments.DoctorId 
                                AND DoctorFacility.DoctorFacilityId = Appointments.FacilityId 
                                AND DoctorFacility.DoctorFacilityId = Appointments.ResourceId

您正在使用DoctorFacility.DoctorFacilityId进行这些比较的每个。您应该使用JOIN上的相应列。这肯定是你没有得到任何结果的原因。