简体   繁体   中英

MySQL Complex Arithmetic

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
SELECT od.person, od.amount - COALESCE(ow.amount, 0) AS balance  
FROM (SELECT owed_to AS person, SUM(amount) AS amount FROM debts GROUP BY owed_to) od  
LEFT OUTER JOIN (SELECT owed_by AS person, SUM(amount) AS amount FROM debts GROUP BY owed_by) ow  
ON od.person = ow.person
UNION  
SELECT owed_by, SUM(amount) * (-1) FROM debts   
WHERE owed_by NOT IN (SELECT DISTINCT owed_to FROM debts)   
GROUP BY owed_by; 
SELECT `owed_by`, SUM(`amount`) as 'Total Debt'.
(select sum(amount) from debts d2 where d1.owed_by = d2.owed_to) as `Total Plus`
FROM `debts` d1
GROUP BY `owed_by`
ORDER BY SUM(`amount`) DESC

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM