Skip to content
Advertisement

Conditional debit from credits and running balance using SQL

I’ve data like below in a table cryptotransactionledger

id transaction_typeid transaction_type amount totalcoins
1 1 bitcoin-credit 30 30
2 2 ethereum-credit 20 50

If I spend bitcoin, I’m putting a new entry like below in the same table with transaction_typeid 3 and similarly for ethereum with transaction_typeid 4

id transaction_typeid transaction_type amount totalcoins
1 1 bitcoin-credit 30 30
2 2 etherium-credit 20 50
3 3 bitcoin-debit -10 40
4 4 etherium-debit -5 35

Suppose if my final data in the table is like below, I will have 35 bitcoin and 20 ethereum remaning.

id transaction_typeid transaction_type amount totalcoins
1 1 bitcoin-credit 30 30
2 2 etherium-credit 20 50
3 3 bitcoin-debit -10 40
4 4 etherium-debit -5 35
5 1 bitcoin-credit 15 50
6 2 etherium-credit 10 60
7 4 etherium-debit -5 55

How can I arrive at below balance summary using SQL after reducing all debits from respective credits

id transaction_type amount totalcoins
1 bitcoin-credit 35 35
2 etherium-credit 20 55

Advertisement

Answer

Thanks to all those gave suggestions and different solutions. I’ve finally used below query that provides me the results as expected.

Link to DB Fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement