我如何为下面的代码进行重构以提高速度?

时间:2017-01-05 11:23:17

标签: sql sql-server sql-server-2008 tsql

此代码由我的同事开发。它真的很慢。我需要一些帮助才能让它变得更好。我不想创建任何临时表。你能帮我解决一下如何更快地进行查询吗?

SELECT s.MaterialNumber
    ,sum(s.Stock) Stock
    ,dbo.getSapContractNumberBySapDeliveryNumber(s.SapDeliveryNumber) SapContractNumber
    ,s.BillTo
    ,s.Quantity
INTO #tmp
FROM Stok s
GROUP BY s.MaterialNumber
    ,s.SapDeliveryNumber
    ,s.BillTo
    ,s.Quantity

SELECT DISTINCT e.SapContractNumber + '' + e.CustomerId Id
    ,e.SapContractNumber
    ,c.ContractName
    ,e.CustomerId
    ,cu.CustomerFullName
    ,e.ortalamastok
    ,(
        SELECT COUNT(*)
        FROM Orders o
        WHERE o.CustomerId = e.CustomerID
            AND o.SapContractNo = e.SapContractNumber
            AND o.OrderDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
                AND DATEADD(MONTH, DATEDIFF(MONTH, - 1, GETDATE()), - 1)
        ) OrderCount
FROM EmniyetStok e
LEFT JOIN #tmp t ON t.SapContractNumber = e.SapContractNumber
LEFT JOIN Customers cu ON cu.CustomerID = e.CustomerID
LEFT JOIN Contracts c ON c.SAPContractNumber = e.SapContractNumber
WHERE {0}
    AND e.ortalamastok > 0

DROP TABLE #tmp

1 个答案:

答案 0 :(得分:1)

    SELECT 
     s.MaterialNumber
    ,sum(s.Stock) Stock
    ,dbo.getSapContractNumberBySapDeliveryNumber(s.SapDeliveryNumber) SapContractNumber
    ,s.BillTo
    ,s.Quantity
INTO #tmp
FROM Stok s
GROUP BY s.MaterialNumber
    ,s.SapDeliveryNumber
    ,s.BillTo
    ,s.Quantity

CREATE UNIQUE CLUSTERED INDEX IX_SapContractNumber_tmp on #tmp (SapContractNumber)

SELECT 
    Qry.Id,
    Qry.SapContractNumber,
    Qry.ContractName,
    Qry.CustomerId,
    Qry.CustomerFullName,
    Qry.ortalamastok,
    COUNT(Qry.OrderID) TotalCount
FROM
    (
        SELECT DISTINCT 
            e.SapContractNumber + '' + e.CustomerId AS Id   
            ,e.SapContractNumber
            ,c.ContractName
            ,e.CustomerId
            ,cu.CustomerFullName
            ,e.ortalamastok
            ,o.OrderID -- change appropriate column name here
        FROM EmniyetStok e
        INNER JOIN Orders o
        ON o.CustomerId = e.CustomerID
        AND o.SapContractNo = e.SapContractNumber
        AND o.OrderDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
        AND DATEADD(MONTH, DATEDIFF(MONTH, - 1, GETDATE()), - 1)
        LEFT JOIN #tmp t ON t.SapContractNumber = e.SapContractNumber
        LEFT JOIN Customers cu ON cu.CustomerID = e.CustomerID
        LEFT JOIN Contracts c ON c.SAPContractNumber = e.SapContractNumber
        WHERE {0} AND e.ortalamastok > 0
) Qry
GROUP BY 
    Qry.Id,
    Qry.SapContractNumber,
    Qry.ContractName,
    Qry.CustomerId,
    Qry.CustomerFullName,
    Qry.ortalamastok    
DROP TABLE #tmp