This query works, but is there a better way to write this query? The current one seems slow. The scenario is very straight forward.
I have two tables, Customers and Payments. The Customers table has what you would expect with Customer info. The Payments table keeps track of the monthly payments that a Customer makes. It has a few fields we need to look at - DueDate, PaymentDate, and CustomerID.
The query I want is I want all Customers who were late by at least 3 months in their first 12 payments. The query I have is below, but it seems to be pretty slow. Is there a better way to write this, than what I have below?
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 )
Thanks!