I am trying to work out a rather complicated query in SQL Server 2008. I would like to get SQL experts here.
Imagine that I had a payment table with these fields:
PaymentID int, CustomerID int, Date and time of sending PaymentDate, Decimal amount
In fact, this is a table of payments made by the client on specific dates. It is important to note that in some cases the payment amount may be negative. Thus, over time, the total amount paid by any client may increase or decrease.
What we are trying to figure out is SQL to calculate the maximum amount of the total amount paid for the client.
So, if Fred made 3 payments: first for $ 5, the second for $ 5, the third for $ 3. The report will show that the total amount paid for the Fred peak was $ 10 (on his second payment), and his final amount paid was $ 7.
We need to run this report for hundreds of thousands of customers (who could potentially make from one to a thousand payments each), so it should be fast.
Is there a good way to structure this query without saving the current totals in db? We would like to avoid storing previously calculated values, if at all possible.
Linus
source share