I have a MySQL table set up like the following:
debts
--------------------------
owed_by | owed_to | amount
--------|---------|-------
Alice | Bob | 5
Bob | Jane | 10
Alice | Jane | 10
Jane | Bob | 5
Is it possible in MySQL to write a query to return the total of what each person owes? Who they owe it to isn't important, I would just like to return each person and (total person owes - total person is owed)
Getting the total owed is easy enough
SELECT `owed_by`, SUM(`amount`) as 'Total Debt'
FROM `debts`
GROUP BY `owed_by`
ORDER BY SUM(`amount`) DESC
but I can't figure out how to subtract what they are owed.
Also, as a general rule, is it better to perform action like this in MySQL (if possible) or PHP?
Here is a SQL Fiddle with my sample data: http://sqlfiddle.com/#!2/dd7cf/1
You can combine both sides:
select Person, sum(debt) as 'Total Debt'
from (
select owed_by as 'Person', amount as 'debt'
from debts
union all
select owed_to, -1*amount
from debts
) as q
group by Person;
SELECT owed.owed_by, owed.amount - coalesce(owns.amount, 0) as `Total Debt`
FROM (
select owed_by, sum(amount) as amount
from debts
group by owed_by
) owed
left join (
select owed_to, sum(amount) as amount
from debts
group by owed_to
) owns on owed.owed_by = owns.owed_to
ORDER BY `Total Debt` DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With