I have a MySQL table of billing records. Each entry records either a payment or a charge, the amount, the date applied, and the related customer id. If there are more charges than payments, how can I get the outstanding charge records sorted by most recent, and if there are more payments than charges, the payment credits sorted by most recent? Basically, if I have 3 rows of charges amounting to $1.25 each, and 2 rows of $1.50, how can I get the 3 charge record that is the most recent, and know that there is only $0,75 left due? I hope that makes sense.
Let’s say we have this table:
user_id | amount | date_applied | type
---------------------------------------
1 1.25 *datetime* -
1 1.25 *datetime* -
1 1.25 *datetime* -
1 1.50 *datetime* +
1 1.50 *datetime* +
the result should be something similar to this:
user_id | amount | date_applied | type
---------------------------------------
1 0.75 *datetime* -
I may not even be thinking about this right. I am open to other suggestions
Your question is a bit tricky. That’s because there is no clear definition on what datetime to show. It seems you want to have the sum of all positive and negative values on the table per user. The problem is that when you make a total you can’t have a detail of the datetimes. You will have to choose one of them, but there won’t be any order in the result as there will only be one datetime per user in the result (in your example you can see for user 1 there is only one datetime).
Also, do you need the type column? Why not add it to the amount?
This is the closest I can get to your needs given the detail provided:
Note: If you really need the datetime put a real date for each record and update the expected result with the expected date value.