I'm looking at different blockchain transactions and wanted to create a running balance of a given asset based on INPUT_ADDRESS
(the address sending the currency) INPUT_AMOUNT
(the amount being sent by an INPUT_ADDRESS), OUTPUT_ADDRESS
(the address receiving the currency) and OUTPUT_AMOUNT
(the amount being received by an OUTPUT_ADDRESS)
Here's a sample of a table I'm using:
BLOCK_DATE | BLOCK_HEIGHT | TRANS_HASH | INPUT_ADDRESS | OUTPUT_ADDRESS | INPUT_AMOUNT | OUTPUT_AMOUNT
01/11/2020 190 15c7853 abc xyz1 -0.01 0.0001
01/11/2020 190 14v9876 abc xyz2 -0.50 0.70
01/11/2020 191 19vc842 abc xyz3 -5.03 0.413
01/12/2020 192 20ff4d3 abc xyz4 -0.06 0.201
01/12/2020 192 154gf34 xyz1 abc -0.07 0.18
01/12/2020 192 45f4ti5 ggg abc -0.10 0.24
01/12/2020 192 33cv5c5 jjj abc -0.08 1.13
If I were to calculate a running sum of address abc
, what's an efficient way of going about this? I tried using something like:
SELECT BLOCK_DATE, BLOCK_HEIGHT, TRANS_HASH, INPUT_ADDRESS, OUTPUT_ADDRESS, INPUT_AMOUNT, OUTPUT_AMOUNT, SUM (INPUT_AMOUNT) OVER (ORDER BY DATE) AS RunningAgeTotal
FROM TRANSACTION_TABLE
WHERE INPUT_ADDRESS = abc
In this particular example, the total balance for abc would be the sum of OUTPUT_AMOUNT where abc is the OUTPUT_ADDRESS (ie 0.18 + 0.24 + 1.13) + the sum of INPUT_AMOUNT where abc is the INPUT_ADDRESS (ie -0.01 + -0.50 + -5.03 + -0.06). So, 1.55 + (-5.60) = -4.05
But I don't think this is the right way of going about this and I'm not sure how to account for the OUTPUT_AMOUNT (eg when abc receives is an OUTPUT_ADDRESS and receives an OUTPUT_AMOUNT)
Is this what you want?
select t.*,
sum(case when input_address = 'ABC' then input_amount
when output_address = 'ABC' then output_amount
end) over (order by block_date) as running_amount
from transaction_table t
where 'ABC' in (input_address, output_address);
This is a cumulative sum of the amounts aligned with the input/output columns.
EDIT:
You may want:
sum(case when input_address = 'ABC' then input_amount
when output_address = 'ABC' then output_amount
end) over (order by block_date, block_height) as running_amount
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.