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
1 Answer