I'm trying to work out a pretty complex query in SQL Server 2008. I'd like some input from SQL experts here.
Imagine I had a Payments table with these fields:
PaymentID int, CustomerID int, PaymentDate datetime, Amount decimal
So essentially, it is a table of payments made by a customer on specific dates. An important thing to note is that in some cases, a payment amount can be a negative value. So, over time, the total amount paid by any given customer, can go up or down.
What we're trying to figure out is the SQL to calculate the high point of the total amount paid per customer.
So, if Fred made 3 payments: first for $5, second for $5, third for -$3. The report will show that Fred's peak total paid amount was $10 (on his second payment), and his final paid amount was $7.
We need to run this report for a hundred thousand customers (who've potentially made a hundred to a thousand payments each), so it's got to be fast.
Is there a good way to structure this query without storing the running totals in the db? We'd like to avoid storing precalculated values if at all possible.