使用NOT IN花费很长时间的SQL查询

时间:2019-02-26 03:16:34

标签: tsql

我很确定问题在于datetime比较,因为当我删除它时,它的工作速度更快。有人可以指导我吗也可以是NOT IN,因为带有IN子句的类似查询效果很好,是否可以编写此查询以产生相同的结果呢?

with HT as (
            SELECT LEFT(E.patient_urno,1) as 'HTHospitalcode',RIGHT(E.patient_urno, LEN(E.patient_urno) - 1) 'HTRUno' , E.patient_urno 'HTpatient_urno',E.en_system_code 'HTen_system_code',CAST(start_dtm as date) 'HTstart_dtm' ,E.*
            FROM dbo.rpt_Encounter E JOIN [dbo].[rpt_V_DataSource_HTRK_Latest] DS ON DS.DatasourceID =  E.DatasourceID
                                         JOIN [dbo].[rpt_Patient] P ON E.PatientID = P.PatientID
            WHERE ISNULL(P.patient_urno,'') <> ''
                AND  (LEN(P.patient_urno) BETWEEN 6 AND 8)
                AND NOT ( P.patient_urno LIKE '9999999' OR P.patient_urno LIKE '99999999' )
                AND  (E.locations  LIKE 'Box Hill Cath Labs')
                AND (start_dtm) IS NOT NULL
                ), HIP as 


             (SELECT 
                          LEFT(DS1.Hospital_Code,1) 'HIPHospitalCode',P1.patient_urno 'HIPURno',LEFT(DS1.Hospital_Code,1)+E1.patient_urno 'HIPpatient_urno',E1.en_system_code 'HIPen_system_code',cast(start_dtm as date) 'HIPstart_dtm', cast(end_dtm as date)'HIPend_dtm' 
                      FROM 
                          [dbo].[rpt_Encounter] E1
                          JOIN [dbo].[rpt_V_DataSource_HOMR_IP_Latest] DS1 on DS1.[DataSourceID] = E1.[DataSourceID] 
                          LEFT JOIN [dbo].[rpt_Patient] P1 ON E1.PatientID = P1.PatientID 
                      WHERE 
                          ISNULL(P1.patient_urno, '') <> '' )


    SELECT DISTINCT * FROM HT where HTpatient_urno NOT IN (SELECT HIPpatient_urno FROM HIP WHERE HTstart_dtm BETWEEN HIPstart_dtm AND HIPend_dtm)

1 个答案:

答案 0 :(得分:0)

这可以更快:

SELECT DISTINCT * FROM HT WHERE NOT EXISTS (SELECT 1 FROM HIP WHERE HTstart_dtm BETWEEN HIPstart_dtm AND HIPend_dtm AND HTpatient_urno = HIPpatient_urno)

您还在日期和“ urno”列上建立索引吗?