Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the remaining amount per row?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 the ORDER BY to get the right amount

SELECT
`id`, `user_id`, `amount`
, SUM(`amount`) OVER(PARTITION BY `user_id` ORDER BY `id`) run_sum
  FROM wallet
id user_id amount run_sum
1 5 1000 1000
2 5 -200 800
3 5 -100 700
4 5 500 1200

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading