选择具有多个内部联接的不同

时间:2018-08-16 21:41:54

标签: sql sql-server

我正在尝试提取患者列表,并且需要排除所有重复的SubscriberNumber值。我可以在不使用Where(Primary_Insurance.SubscriberNumber =的情况下使用Select Distinct子句,并且可以正常工作。将(Primary_Insurance.SubscriberNumber =)添加到查询中时,它将忽略我的日期范围,并拉出所有与SubscriberNumber相关的约会

SELECT   Primary_Insurance.SubscriberNumber,  Encounter.DTTM, Patient_Iorg.OrganizationMrn AS MRN, Patient_Contact.HomePhoneArea, Patient_Contact.HomePhoneExchange, Patient_Contact.HomePhoneLast4, 
         Patient_Contact.LastName, Patient_Contact.FirstName, Patient_Contact.AddressLine1, Patient_Contact.AddressLine2, Patient_Contact.City, Patient_Contact.State, Patient_Contact.Zip, 
         Appointment.AppointmentStatusDE
FROM            Appointment INNER JOIN
                     Encounter ON Appointment.PatientID =   Encounter.PatientID INNER JOIN
                     Patient_Iorg INNER JOIN
                     Patient_Contact ON Patient_Iorg.PersonID = Patient_Contact.PatientID INNER JOIN
                     Primary_Insurance ON Patient_Iorg.PersonID = Primary_Insurance.patientid ON Encounter.PatientID = Primary_Insurance.patientid
WHERE           (Encounter.DTTM > CONVERT(DATETIME, '2018-06-15 00:00:00', 102)) AND (Encounter.DTTM >= CONVERT(DATETIME, '2018-12-31 00:00:00', 102)) AND (Appointment.AppointmentStatusDE = 4) AND 
                     (Primary_Insurance.SubscriberNumber = '19803782') OR
                     (Primary_Insurance.SubscriberNumber = '19835428') OR
                     (Primary_Insurance.SubscriberNumber = '19914818') OR
                     (Primary_Insurance.SubscriberNumber = '19993082') OR
                     (Primary_Insurance.SubscriberNumber = '19993082') OR
                     (Primary_Insurance.SubscriberNumber = '19993082')
group BY             Primary_Insurance.SubscriberNumber, Encounter.DTTM, Patient_Iorg.OrganizationMrn, Patient_Contact.HomePhoneArea, Patient_Contact.HomePhoneExchange, Patient_Contact.HomePhoneLast4, 
                     Patient_Contact.LastName, Patient_Contact.FirstName, Patient_Contact.AddressLine1, Patient_Contact.AddressLine2, Patient_Contact.City, Patient_Contact.State, Patient_Contact.Zip, 
                     Appointment.AppointmentStatusDE;

需要弄清楚如何将Distinct与多个Where子句和内部联接一起使用

1 个答案:

答案 0 :(得分:2)

大概,您想要的逻辑是:

WHERE Encounter.DTTM > '2018-06-15' AND 
      Encounter.DTTM >= '2018-12-31' AND
      Appointment.AppointmentStatusDE = 4 AND 
      Primary_Insurance.SubscriberNumber IN ('19803782', '19835428', '19914818', '19993082', '19993082', '19993082')

您的查询存在问题,因为OR条件周围没有括号。但是,IN比括号更简单,更清楚了。

请注意,我更改了日期常量。 SQL Server非常擅长将值转换为日期。我觉得这更具可读性。