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.

WITH cte1
 AS (SELECT a.*,
            CASE
              WHEN ( transaction_typeid = 1
                      OR transaction_typeid = 3 ) THEN 0
              ELSE 1
            END AS category
     FROM   cryptotransactionledger a
     ORDER  BY id),
 cte2
 AS (SELECT CASE
              WHEN ( category = 0 ) THEN 'bitcoin-credit'
              ELSE 'etherium-credit'
            END         AS transaction_type,
            Sum(amount) AS amount
     FROM   cte1 o
     GROUP  BY category),
 cte3
 AS (SELECT Row_number()
              OVER (ORDER BY c.transaction_type) AS id,
            c.*
     FROM   cte2 c) SELECT f.*,
     Sum(amount) OVER(ORDER BY f.id) AS total_coins FROM cte3 f;

Link to DB Fiddle

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