Alternative of Cursor in SQL Server 2005
Hi,
I have a table which contain following fields
account_no,
Payment_date,
Payment-Amount
Now this table contain all the history of all accounts for payments.
So if any account member has paid bills 100 times there are 100 rows for that and so on for all accounts.
Now I have to display the latest payment date and amount for all accounts.
So I am using the cursor for that, but the cursor is taking lot of minutes due to the large number of accounts.
So please tell me the alternative for this problem.
Working with payment histories
Because payments are sometimes received on the same day, max(date) may not produce the desired results when 're-joining' to the original table...
Try something like this:
Select Id, Date, Amt
From
(Select row_number() Over (Partition By Id Order by Date desc, Amt) as PayDateOrder, Id, Date, Amt
From PymtTable) OrderedPymts
Where PayDateOrder = 1
By pre-ordering the payments (most recent set to 1), and then looking at only payments numbered as 1, all fields from the most recent payment row are now available to you.