Microsoft Access-子查询运行非常慢

时间:2018-11-11 19:19:50

标签: sql ms-access

我试图在每个期末为每个客户汇总12个月的总收入。期间表在每个要求的期间为每位客户提供一行。

查询如下-可以运行,但运行速度非常慢。

SELECT Periods.LTM_Start, Periods.Period_End, Periods.sa_account,
 (SELECT Sum(sa_trvalue) FROM [Sales Transactions]
    WHERE ((sa_trdate<= Periods.[Period_End])
    AND (sa_trdate>= Periods.[LTM_Start]) )
    AND 
    [Sales Transactions].sa_account = Periods.[sa_account]
    AS Total

FROM Periods
GROUP BY Periods.LTM_Start, Periods.Period_End, Periods.sa_account;

1 个答案:

答案 0 :(得分:1)

由于您使用相关子查询,因此查询的评估速度较慢,因此会针对Sales Transactions每条记录评估引用Periods表的查询桌子。

您应该能够通过适当地使用联接来提高性能,例如,类似以下内容的结果应该相同:

SELECT 
    Periods.LTM_Start, 
    Periods.Period_End, 
    Periods.sa_account, 
    SUM
    (
        IIF
        (
            [Sales Transactions].sa_trdate >= Periods.[LTM_Start] AND 
            [Sales Transactions].sa_trdate <= Periods.[Period_End],
            [Sales Transactions].sa_trvalue,
            0
        )
    ) AS Total
FROM
    Periods LEFT JOIN [Sales Transactions] 
    ON [Sales Transactions].sa_account = Periods.[sa_account]
GROUP BY 
    Periods.LTM_Start, Periods.Period_End, Periods.sa_account;