Skip to content
Advertisement

How can I refactor the below code to make it faster?

This code is developed by my colleague, and it is really slow. I don’t want to create any temp table. How can I make this query faster?

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

Advertisement

Answer

    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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement