Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Complex Arithmetic

Tags:

math

mysql

logic

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

like image 444
Robert Avatar asked Mar 13 '26 19:03

Robert


2 Answers

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;
like image 140
slaakso Avatar answered Mar 15 '26 09:03

slaakso


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
like image 29
Clodoaldo Neto Avatar answered Mar 15 '26 09:03

Clodoaldo Neto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!