如何优化此查询-替换/优化NOT IN

时间:2019-06-25 14:18:10

标签: sql sql-server tsql

查询应返回顶部不包含的值-例如-10。 无论如何进行优化?也许替换成NOT IN?

CREATE PROCEDURE procName 
    @ClientId char(36)
    , @Top int
    , @StartDate datetime
    , @EndDate datetime
AS
BEGIN
    SELECT
        'Outside' AS LocationName
        , SUM(Copies * Pages) AS TotalPages
    FROM table1 tb1 
    INNER JOIN table2 tb2 ON tb2.Tb2Id = tb1.Tb2Id 
    INNER JOIN [table3] tb3 ON tb3.LocationId = tb2.LocationId
    WHERE tb1.ClientId = @ClientId AND tb1.TimeOrdered BETWEEN @StartDate AND @EndDate
        AND tb3.[Name] NOT IN (
            SELECT TOP(@Top)
                tb3.[Name] AS LocationName
            FROM table1 tb1 
            INNER JOIN table2 tb2 ON tb2.Tb2Id = tb1.Tb2Id 
            INNER JOIN [table3] a ON tb3.LocationId = tb2.LocationId
            WHERE tb1.ClientId = @ClientId AND tb1.TimeOrdered BETWEEN @StartDate AND @EndDate
            GROUP BY tb3.Name
            ORDER BY SUM(tb1.Copies * tb1.Pages) DESC   
        )
END

1 个答案:

答案 0 :(得分:1)

您可以尝试:

SELECT
    'Outside' AS LocationName
    , SUM(Copies * Pages) AS TotalPages
FROM table1 tb1 
INNER JOIN table2 tb2 ON tb2.Tb2Id = tb1.Tb2Id 
INNER JOIN [table3] tb3 ON tb3.LocationId = tb2.LocationId
left outer join 
(
            SELECT TOP(@Top)
                tb3.[Name] AS LocationName
            FROM table1 tb1 
            INNER JOIN table2 tb2 ON tb2.Tb2Id = tb1.Tb2Id 
            INNER JOIN [table3] a ON tb3.LocationId = tb2.LocationId
            WHERE tb1.ClientId = @ClientId AND tb1.TimeOrdered BETWEEN @StartDate AND @EndDate
            GROUP BY tb3.Name
            ORDER BY SUM(tb1.Copies * tb1.Pages) DESC  
) z on z.LocationName = tb3.LocationName
WHERE tb1.ClientId = @ClientId AND tb1.TimeOrdered BETWEEN @StartDate AND @EndDate
and z.LocationName is null

这摆脱了NOT IN,但并没有删除看起来仍然需要的选择TOP。

在不知道可用索引以及所涉及表中的行数的情况下,没有更多的人可以将您作为问题注释中的注释告诉您了。