I would like to make improvement to my existing query below.
First of all, when the tables are still relatively small, the below query ran fine and fast.
But as time goes by, the tables keep getting larger and larger everyday. Therefore, the query is running longer and longer.
I would like to find the alternative ways to improve my query below as now the query is running very long.
My objective is; I want to retrieve the most recent LoanNumber inserted into the table everyday.
Example of data in the table:
1)
LoanNumber 30495
DateSt 2022-12-18
LoanNumber 30495
DateSt 2022-12-17
2)
LoanNumber 30494
DateSt 2022-12-18
3)
LoanNumber 30489
DateSt 2022-12-16
When I run the below query, I should get the following results:
LoanNumber 30495
DateSt 2022-12-18
LoanNumber 30494
DateSt 2022-12-18
LoanNumber 30489
DateSt 2022-12-16
There is a clustered-index on LoanNumber and DateSt in each of the table.
SELECT DISTINCT
li.DateSt
,li.LoanNumber
,LoanStatus.Status
FROM [ARCUSERV].[OpenClose_Live_v1].[dbo].[1003LoanInfo] li
INNER JOIN (SELECT loannumber, MAX(DateSt) as MaxDate
FROM [ARCUSERV].[OpenClose_Live_V1].[dbo].[1003LoanInfo]
GROUP BY LoanNumber
) latestloan on li.LoanNumber = latestloan.LoanNumber and li.DateSt = latestloan.MaxDate
LEFT OUTER JOIN [ARCUSERV].[OpenClose_Live_V1].[dbo].[Misc] LoanStatus
ON LoanStatus.LoanNumber = li.LoanNumber
AND LoanStatus.[DateSt] = (SELECT MAX(DateST) FROM [ARCUSERV].[OpenClose_Live_V1].[dbo].[Misc] WHERE LoanNumber = li.[LoanNumber])
I am wondering if there's better way to improve the above query.
Thank you in advance for your help.