SQL查询运行需要10多分钟,分成两半需要26秒

时间:2017-10-12 13:51:48

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

我正在编写一个SQL查询来提取制造数据并计算出每月与输出相比的成本。查询结构庞大(超过4个查询超过200行)。运行需要5分钟。我不认为我实际上让它完全运行。

生产成本部分需要13秒才能运行。我无法理解如何运行报告的其余部分需要这么长时间。因此,将生产成本转储到表中并使用该表运行销售报告。瞧!现在销售报告需要13秒!

现在我怎样才能让我的查询只需要26秒才能运行?

以下是销售报表查询中提取生产成本的行。 [Production Cost Per Job]是生产成本查询。

OUTER APPLY (
    SELECT TOP 1
        bpc.StartingMonth,  
        bol.[Item No_] as ItemNo, 
        SUM(bpc.Amount) / SUM(bpc.Quantity) as Cost
    FROM "Production Output Line" as bol
    INNER JOIN [Production Cost Per Job] as bpc
        ON bol.[JobID] = bpc.[JobID]
        AND bol."Output Item Size" = bpc.ItemSize
        AND DATEDIFF(mm, 0, bol.[Starting Date]) = bpc.StartingMonth
    WHERE bpc.Quantity <> 0 
    AND bpc.StartingMonth <= a.MonthDate
    AND bpc.StartingMonth >= 1380 -- January 2015
    AND bol.[Item No_] = a.ItemNo
    GROUP BY bpc.StartingMonth, bol.[Item No_]
    ORDER BY bpc.StartingMonth
) as b 

1 个答案:

答案 0 :(得分:1)

根据您的逻辑,我认为以下内容可以非常有效地工作(我不知道您在a中拥有什么,所以我也创建了a.a_rows作为MonthDate字段:

SELECT
    a_rows
    , MonthDate
    , StartingMonth
    , ItemNo
    , Cost
FROM
    (
        SELECT
            a_rows
            , MonthDate
            , StartingMonth
            , ItemNo
            , Cost
            , ROW_NUMBER() OVER (PARTITION BY a_rows, MonthDate ORDER BY StartingMonth) R
        FROM
            (
                SELECT
                    a.a_rows
                    , a.MonthDate
                    , bpc.StartingMonth
                    , bol.[Item No_] ItemNo
                    , SUM(bpc.Amount) / SUM(bpc.Quantity) Cost
                FROM
                    [a] a
                    LEFT JOIN [Production Output Line] bol ON bol.[Item No_] = a.ItemNo
                    LEFT JOIN [Production Cost Per Job] bpc ON
                        bpc.StartingMonth <= a.MonthDate
                        AND bpc.StartingMonth >= 1380
                        AND bpc.Quantity <> 0
                GROUP BY
                    a.a_rows
                    , a.MonthDate
                    , bpc.StartingMonth
                    , bol.[Item No_]
            ) Q
    ) Q2
WHERE R = 1