I have a wallet
table like this:
// wallet
+----+----------+--------+
| id | user_id | amount |
+----+----------+--------+
| 1 | 5 | 1000 |
| 2 | 5 | -200 |
| 3 | 5 | -100 |
| 4 | 5 | 500 |
+----+----------+--------+
I want to make a view
that calculates the remaining amount per row. Something like this:
+----+----------+--------+------------------+
| id | user_id | amount | remaining_amount |
+----+----------+--------+------------------+
| 1 | 5 | 1000 | 1000 |
| 2 | 5 | -200 | 800 |
| 3 | 5 | -100 | 700 |
| 4 | 5 | 500 | 1200 |
+----+----------+--------+------------------+
Any idea how can I do that?
2
Answers
Do not know if this meets your demands or not
MySQL 8 has window function for that purpose, like
SUM() OVER
for your sample data, this will calculate the running SUM for every user_id
vital for th function to work is the
PARTITION BY
and theORDER BY
to get the right amountThe
PARTITION BY
is used to get sums for a user_id, so if you had user 5,6,7,8 it will correctly add (or subtract) the maount theat that user produced.The
ORDER BY
is needed to get the right mount at the corect position. Tables are by nature unsortede, so anORDER BY
is needed to give the outout the corect order, if the ids where changed, you would get another mount, as it will be prior added to the running sumfiddle