Skip to content
Advertisement

how to get the balance of each participant from transfer table using one select query?

I have a transfer table which looks like this:

transfer

enter image description here

I would like to get the balance of each participant from the transfer table.

The output of the query should looks like this:

output

enter image description here

Advertisement

Answer

You could try with something like this:

select sender,(select sum(amount)
               from table1 b
               where b.recipient=a.sender)-sum(amount)
from table1 a
group by sender

Where you get for every sender the sum of the amount he has given as a sender minus the sum of the amount he has got as receiver.

EDIT Some one told me that the sum was inverted and he was right, so I changed the order of the operands

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