使用 NOT IN 时如何提高查询性能

How to improve query performance when using NOT IN

我正在连接两个表的多对多关系。

在我的最终结果中,每个 PolicyNumber 都有多个 ClassCode。 看起来像这样:

现在,如果选择了 SSRS 中的 @ClassCode 参数,我需要用 PaidLosses 排除整个 PolicyNumber。 所以,当我使用 NOT IN 消除 PolicyNumber 它永远旋转。

select      
            cte1.PolicyNumber,
            cte1.TransactionEffectiveDate,
            cc.ClassCode,
            CASE
                WHEN ROW_NUMBER() OVER (PARTITION BY cte1.QuoteID, cte1.PolicyNumber, cc.TransactionEffectiveDate ORDER BY (SELECT 0))=1 THEN cte1.WP 
                ELSE 0
            END  as WP--,
from        cte1 inner join tblClassCodesPlazaCommercial cc on cte1.PolicyNumber=cc.PolicyNumber AND cte1.QuoteID=cc.QuoteID AND cte1.TransactionEffectiveDate=cc.TransactionEffectiveDate
            AND cc.PolicyNumber IN (SELECT PolicyNumber FROM tblClassCodesPlazaCommercial WHERE ClassCode NOT IN (@ClassCode))

对于我的情况,还有其他方法可以提高查询性能吗?

整个查询如下:

DECLARE @ClassCode int = 5151
;with cte1
as
(
SELECT      QuoteID,
            CONVERT(VARCHAR(10),TransactionEffectiveDate,101) as TransactionEffectiveDate,
            PolicyNumber,
            SUM(WrittenPremium) as WP                           
FROM        PlazaInsuranceWPDataSet    

WHERE        State IN ('CA','NV','AZ') 
GROUP BY    
            PolicyNumber,
            QuoteID,
            TransactionEffectiveDate    
),
cte3
as
(
select      
            cte1.PolicyNumber,
            cte1.TransactionEffectiveDate,
            cc.ClassCode,
            CASE
                WHEN ROW_NUMBER() OVER (PARTITION BY cte1.QuoteID, cte1.PolicyNumber, cc.TransactionEffectiveDate ORDER BY (SELECT 0))=1 THEN cte1.WP 
                ELSE 0
            END  as WP--,
from        cte1 inner join tblClassCodesPlazaCommercial cc on cte1.PolicyNumber=cc.PolicyNumber AND cte1.QuoteID=cc.QuoteID AND cte1.TransactionEffectiveDate=cc.TransactionEffectiveDate
            AND cc.PolicyNumber IN (SELECT PolicyNumber FROM tblClassCodesPlazaCommercial WHERE ClassCode NOT IN (@ClassCode))
)
select  
        c.YearNum,
        c.MonthNum, 
        SUM(WP) as WP         
from    cte3 RIGHT JOIN tblCalendar  c ON c.YearNum=YEAR(TransactionEffectiveDate) AND c.MonthNum=MONTH(TransactionEffectiveDate)
WHERE   c.YearNum <>2017
GROUP BY    
            c.YearNum,
            c.MonthNum
ORDER BY    c.YearNum desc,
            c.MonthNum

对于CTE3,我觉得你可以这样写,对提高性能有帮助

cte3
as
(
select      
            cte1.PolicyNumber,
            cte1.TransactionEffectiveDate,
            cc.ClassCode,
            CASE
                WHEN ROW_NUMBER() OVER (PARTITION BY cte1.QuoteID, cte1.PolicyNumber, cc.TransactionEffectiveDate ORDER BY (SELECT 0))=1 THEN cte1.WP 
                ELSE 0
            END  as WP--,
from        cte1 
inner join tblClassCodesPlazaCommercial cc 
on cte1.PolicyNumber=cc.PolicyNumber 
    AND cte1.QuoteID=cc.QuoteID 
    AND cte1.TransactionEffectiveDate=cc.TransactionEffectiveDate

where cc.ClassCode NOT IN (@ClassCode))
    )