SQL查询优化,查看前x个记录

时间:2015-03-23 14:54:29

标签: sql sql-server

此查询有效,但是有更好的方法来编写此查询吗?目前的似乎很慢。这种情况很直接。

我有两个表,即客户和付款。 Customers表具有您对客户信息的期望。付款表会跟踪客户的每月付款。它有一些我们需要查看的字段 - DueDate,PaymentDate和CustomerID。

我想要的查询是我希望所有在前12次付款中至少迟到3个月的客户。我的查询如下,但似乎很慢。有没有比我下面的更好的方式来写这个?

SELECT  CustomerID
FROM    Customers AS C
WHERE   EXISTS ( SELECT DueDate, CustomerID, PaymentDate
                 FROM   ( SELECT TOP 12 *
                          FROM      Payments as P
                          WHERE     P.CustomerID = C.CustomerID
                          ORDER BY PaymentDate
                        ) AS First12Payments
                 WHERE  DATEDIFF(MONTH, First12Payments.DueDate, First12Payments.PaymentDate) > 3 )

谢谢!

1 个答案:

答案 0 :(得分:3)

嗯,Joe Enos和Brandon评论中的建议很棒。但是,如果您无法添加该列,那么对SQL语句进行2次微小更改可能会使其更快一些。为了使它更好,您可能需要在Payments表中为DueDate和PaymentDate列添加索引。

SELECT  CustomerID
FROM    Customers AS C
WHERE   EXISTS ( SELECT 1 -- no need for a columns list since you only check for existance
    FROM (SELECT TOP 12 DueDate, PaymentDate -- no need for all the columns, only the ones you use
          FROM      Payments as P
          WHERE     P.CustomerID = C.CustomerID
          ORDER BY PaymentDate
         ) AS First12Payments
        WHERE  DATEDIFF(MONTH, First12Payments.DueDate, First12Payments.PaymentDate) > 3